283.ゼロリートコードの移動



283 Moving Zero Leetcode



タイトル説明

配列番号を指定して、ゼロ以外の要素の相対的な順序を維持しながら、すべての0を配列の最後に移動する関数を記述します。

例:
入力:[0,1,0,3,12]
出力:[1,3,12,0,0]



説明:
元のアレイで動作する必要があり、追加のアレイをコピーすることはできません。
操作の数を最小限に抑えます。

ソース:LeetCode
リンク:https://leetcode-cn.com/problems/move-zeroes
著作権は控除ネットワークに帰属します。商業的転載の公式認可に連絡し、非商業的転載の出典を示してください。



問題1

同じ考え この質問 同様ですが、0を割り当てる操作はあと1つだけです。
最初のアイデア:現在の位置の前にあるゼロの数だけ、ゼロ以外の要素を前方に移動します。

コード1

/* The idea is similar to delete the elementless array value 0 It’s just one more step, and assign 0 to the last few elements. */ class Solution { public: void moveZeroes(vector<int>& nums) { int cnt = 0, len = nums.size() for(int i = 0 i < len ++i){//Count the number of 0 and move the element if(nums[i] == 0){ ++cnt } else{ nums[i - cnt] = nums[i] } } for(int i = len - 1 i >= len - cnt --i){//Assign the last few elements to 0 nums[i] = 0 } } }

実行結果1

画像

問題2

ダブルポインタ。1つは元の配列をトラバースするために使用され、もう1つはゼロ以外の要素を元の配列に入力するために使用されます。



コード2

/* Double pointer, one for traversing the original array, the other for assignment */ class Solution { public: void moveZeroes(vector<int>& nums) { int i = 0, j = 0, len = nums.size() for( i < len ++i){ if(nums[i] != 0){ nums[j++] = nums[i] } } for(j j < len ++j){ nums[j] = 0 } } }

の結果

画像