*************
C++
topic:283. 移动零 - 力扣(LeetCode)
*************
Hello, how's your weekend.
during my learning, topic about array perplex me. Just do it.
Inspect the topic:
It is a easy one but not easy for me now because I have no idea anout the pointer.
When talks about sort, use SORT standard library always fine. However this topic, sort doesnot work.
Doble pointer maybe works. nums[j] = nums[i] if nums[i] != 0. Double pointer do work. Make two pointer, pointer i moves faster and pointer j moves slower. And pointer i & pointer j works in the same array.
Then the code is as follow
class Solution {
public:void moveZeroes(vector<int>& nums) {int n = nums.size(); // get the lengthint j = 0;for(int i = 0; i < n; i++){if (nums[i] != 0){nums[j] = nums[i];j++;}}}
};
however this code doesnot works, seeing the result:
seeing the result cannot understood, just hand write the running progress:
nums = 0 1 0 3 2
- i = 0, nums[0] == 0, j = 0, nums = 0 1 0 3 2
- i = 1, nums[1] = 1, nums[0] = 1, j = 1, nums = 1 1 0 3 2
- i = 2, nums[2] == 0, j = 1, nums = 1 1 0 3 2
- i = 3, nums[3] = 3, j = 1, nums[1] = nums[3] = 3, j = 2, nums = 1 3 0 3 2
- i = 4, nums[4] = 2, j = 2, nums[2] = nums[4] = 2, nums = 1 3 2 3 2
So after moving pointer j, make sure that nums[j + 1] ~ nums[n - 1] == 0;
class Solution {
public:void moveZeroes(vector<int>& nums) {int n = nums.size(); // get the lengthint j = 0;for(int i = 0; i < n; i++){if (nums[i] != 0){nums[j] = nums[i];j++;}}for(int i = j; i < n; i++){nums[i] = 0;}}
};
For easy use, introduce a standard library SWAP. The usage of swap is to xechange two viraties position
#include <utility> // 包含swap函数的头文件int a = 10;
int b = 20;
std::swap(a, b); // 交换a和b的值
then the code can be more concise
class Solution {
public:void moveZeroes(vector<int>& nums) {int j = 0;for(int i = 0; i < nums.size(); i++) {if(nums[i] != 0) {swap(nums[i], nums[j]);j++;}}}
};