移动零-283e

未分类
100 词

依旧双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>

void moveZeroes(std::vector<int>& nums) {
int left = 0;
int right = 0;
while (right < nums.size()) {
//当右指针不为零时与左指针互换元素
if (nums[right]) {
int x = nums[left];
nums[left] = nums[right];
nums[right] = x;
right++;
left++;
}
else right++;
}
};

int main() {
std::vector<int> nums = { 0,1,0,3,12 };
moveZeroes(nums);
for (int num : nums) {
std::cout << num << std::endl;
}
}

视频链接:https://www.bilibili.com/video/BV1tZtVeUE2o/?spm_id_from=333.337.search-card.all.click&vd_source=8a00a24977de92674a7b9aebcdcb67f9

力扣:https://leetcode.cn/problems/move-zeroes/description/

留言