leetcode 283_movezeroes

Description

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

一个比较普适的解法,与快排相似,两个指针扫描,不过都是从头开始扫描,一个指针检测非零,一个指针检测零,都检测到时就交换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
void (vector<int>& nums) {
int index = 0;
int zero = 0;
while(zero<nums.size()){
if(nums[zero] != 0 && nums[index] == 0){
for(int i = zero;i> index;i--){swap(nums[i],nums[i-1]);}
}
if(nums[zero] == 0 || (nums[zero]!=0 && zero<=index))zero++;
if(nums[index] != 0)index++;
}
}
};

另一种解法,直接将非零的往前排,到最后再赋0值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
void (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;
}
}
};