283. Move Zeros
Given an arraynums
, write a function to move all0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, givennums = [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.
Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.
FB Followup: 输入是一个array, 有正数和负数,题目要求将正数移动到一侧,负数移动到另一侧。
Thoughts:
Having an pointer to keep track of non-zeros and replace the original value in the array then pad the rest of space with 0
Code
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0;
for(int i = 0 ; i < nums.size(); i++){
if(nums[i]!= 0) nums[j++] = nums[i];
}
for(; j < nums.size();j++){
nums[j] = 0;
}
}
};
FollowUp:
'''Ask if there is 0 in the array!'''
def move(arr): # with/ without 0
i, j = 0, len(arr) - 1
while True:
while i <= j and arr[i] <= 0 : i+= 1
while j >= i and arr[j] >= 0 : j-= 1
if i > j: break
arr[i], arr[j] = arr[j], arr[i]
print(arr)