LeetCode 283 Move Zeroes(すべてのゼロ要素を移動)
翻訳
ぶんせき
最初はゼロ以外の要素をソートするのかと思っていましたが、よく見ると相対的な位置を維持すればいいだけです.それはずっと簡単ですね.
上記の手順では、現在の数字が0であれば操作せず、ゼロでなければ最初のゼロと位置を交換します.
その核心はこの最初のゼロの位置がどのように変化しているのか、最初は0でなくても大丈夫です.
コードに訳すと次のようになります.
コード#コード#
, “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]);
}
}
};