LeetCode 283 Move Zeroes(移動所有的零元素)
阿新 • • 發佈:2019-02-05
翻譯
給定一個數字陣列,寫一個方法將所有的“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 <iostream>
#include <vector>
using namespace std;
void moveZeroes(vector<int>& nums) {
for (int index = 0, current = 0; current < nums.size(); current++) {
if (nums[current] != 0)
swap(nums[index++], nums[current]);
}
}
int main() {
vector<int> 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<int>& nums) {
for (int index = 0, current = 0; current < nums.size(); current++) {
if (nums[current] != 0)
swap(nums[index++], nums[current]);
}
}
};