283. Move Zeroes (Easy)

Given an array nums, write a function to move all 0’s to the end of it
while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your
function, nums should be [1, 3, 12, 0, 0].

Note: You must do this in-place without making a copy of the array.
Minimize the total number of operations.

Solution:

C:

#include

void moveZeroes(int* nums, int numsSize) {
    int i, j, temp;
    for(i = 0; i < numsSize; i++) {
        for(j = 0; j < numsSize - i - 1; j++) {
            if(nums[j] == 0 && nums[j + 1] != 0) {
                temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
}

void showArr(int* nums, int size) {
    int i;
    for(i = 0; i < size; i++) {
        printf("%d ", nums[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {0, 1, 0, 3, 12};
    showArr(arr, 5);
    moveZeroes(arr, 5);
    showArr(arr, 5);
    return 0;
}

283. Move Zeroes (Easy)_第1张图片

冒泡排序,将0移到数组最后面

你可能感兴趣的:(283. Move Zeroes (Easy))