標籤:each esc key lis ini lin text using array
翻譯
給定一個數字數組。寫一個方法將全部的“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.
分析
一開始我還以為是要給非零元素排序呢,後來細緻一看僅僅是保持相對位置不變就好了。
那就easy非常多了呀。
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]); } }};
LeetCode 283 Move Zeroes(移動全部的零元素)