Try   HackMD

LeetCode 283. Move Zeroes

Description

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Constraints

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1

Answer

此題可設idx來記錄不為0的位置,此題只要管idx是否等於i,若一樣就不用更新,若不一樣就更新即可。

//2022_04_26 void moveZeroes(int* nums, int numsSize){ int i = 0, idx = 0; for(i = 0; i < numsSize; i++){ if(nums[i] != 0){ if(i != idx){ nums[idx] = nums[i]; nums[i] = 0; } idx++; } } }

https://leetcode.com/problems/move-zeroes/

tags: Leetcode