translation
给定一个数字数组。写一个方法将全部的“0”移动到数组尾部。同一时候保持其余非零元素的相对位置不变。比如,给定nums = [0, 1, 0, 3, 12],在调用你的函数之后,nums应该变为[1, 3, 12, 0, 0]。备注:你必须就地完毕,不得复制该数组。
最小化总共的操作数。
Given an array nums,Writea function toMove all0' s to the End of it whileMaintaining theRelative order of theNon-zero elements. For example,givenNums = [0,1,0,3, A], AfterCalling your function, nums should be [1,3, A,0,0]. Note:you must do thisinch-placewithoutMaking aCopy of theArray. Minimize theTotal Number ofOperations.
Analysis
At first I thought I was going to order the non-0 elements, and then I looked at it just to keep the relative position unchanged.
That's a lot of easy.
0 1 0 3 A (index = 0, current = 0)1 0 0 3 A (index = 1, current = 1)1 0 0 3 A (index = 1, current = 2)1 3 0 0 A (index = 2, current = 3)1 3 A 0 0 (index = 3, current = 4)
Follow the above steps, the current number is 0 words do not do the operation. If it is not 0 then it will be swapped with the first 0 position.
Its core lies in how the position of the first zero changes. Even if it is not at the beginning of 0 is OK, big deal let this non-zero and oneself exchange position Bai, for example:
1 2 0 3 A (index = 0, current = 0)1 2 0 3 A (index = 1, current = 1)1 2 0 3 A (index = 2, current = 2)1 2 3 0 A (index = 3, current = 3)1 2 3 A 0 (index = 4, current = 4)
Translation into code is:
#include <iostream>#include <vector>using namespace STD;voidMovezeroes ( vector<int>& Nums) { for(intindex =0, current =0; Current < Nums.size (); current++) {if(Nums[current]! =0) Swap (nums[index++], nums[current]); }}intMain () { vector<int>V V.push_back (1); V.push_back (2); V.push_back (0); V.push_back (3); V.push_back ( A); Movezeroes (v); for(AutoI:V) {cout<< I <<" "; }return 0;}
Code
class Solution {public: void moveZeroes(vector<int>& nums) { for (int00; current < nums.size(); current++) { if0) swap(nums[index++], nums[current]); } }};
Leetcode 283 Move zeroes (move all 0 elements)