給定一個數字數組,寫一個方法將所有的“0”移動到數組尾部,同時保持其余非零元素的相對位置不變。
例如,給定nums = [0, 1, 0, 3, 12],在調用你的函數之後,nums應該變為[1, 3, 12, 0, 0]。
備注:
你必須就地完成,不得復制該數組。
最小化總共的操作數。
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.
一開始我還以為是要給非零元素排序呢,後來仔細一看只是保持相對位置不變就好了。那就容易很多了呀。
0 1 0 3 12 (index = 0, current = 0)
1 0 0 3 12 (index = 1, current = 1)
1 0 0 3 12 (index = 1, current = 2)
1 3 0 0 12 (index = 2, current = 3)
1 3 12 0 0 (index = 3, current = 4)
按上面的步驟來,當前的數字是0的話不做操作,非零的話將其與第一個零互換位置。
其核心在於這個第一個零的位置是如何變化的,即便一開始不是0也沒關系,大不了讓這個非零數和自己交換位置呗,比如說:
1 2 0 3 12 (index = 0, current = 0)
1 2 0 3 12 (index = 1, current = 1)
1 2 0 3 12 (index = 2, current = 2)
1 2 3 0 12 (index = 3, current = 3)
1 2 3 12 0 (index = 4, current = 4)
翻譯成代碼就是:
#include
#include
using namespace std;
void moveZeroes(vector& nums) {
for (int index = 0, current = 0; current < nums.size(); current++) {
if (nums[current] != 0)
swap(nums[index++], nums[current]);
}
}
int main() {
vector v;
v.push_back(1);
v.push_back(2);
v.push_back(0);
v.push_back(3);
v.push_back(12);
moveZeroes(v);
for (auto i : v) {
cout << i << " ";
}
return 0;
}
class Solution {
public:
void moveZeroes(vector& nums) {
for (int index = 0, current = 0; current < nums.size(); current++) {
if (nums[current] != 0)
swap(nums[index++], nums[current]);
}
}
};