Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0d5db5a

Browse files
two_pointer: move elem
1 parent 14eb350 commit 0d5db5a

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

‎cpp/leetcode/283.移动零.cpp

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
* @lc app=leetcode.cn id=283 lang=cpp
3+
*
4+
* [283] 移动零
5+
*
6+
* https://leetcode.cn/problems/move-zeroes/description/
7+
*
8+
* algorithms
9+
* Easy (63.80%)
10+
* Likes: 2012
11+
* Dislikes: 0
12+
* Total Accepted: 1.1M
13+
* Total Submissions: 1.7M
14+
* Testcase Example: '[0,1,0,3,12]'
15+
*
16+
* 给定一个数组 nums,编写一个函数将所有 0
17+
* 移动到数组的末尾,同时保持非零元素的相对顺序。
18+
*
19+
* 请注意 ,必须在不复制数组的情况下原地对数组进行操作。
20+
*
21+
*
22+
*
23+
* 示例 1:
24+
*
25+
*
26+
* 输入: nums = [0,1,0,3,12]
27+
* 输出: [1,3,12,0,0]
28+
*
29+
*
30+
* 示例 2:
31+
*
32+
*
33+
* 输入: nums = [0]
34+
* 输出: [0]
35+
*
36+
*
37+
*
38+
* 提示:
39+
*
40+
*
41+
*
42+
* 1 <= nums.length <= 10^4
43+
* -2^31 <= nums[i] <= 2^31 - 1
44+
*
45+
*
46+
*
47+
*
48+
* 进阶:你能尽量减少完成的操作次数吗?
49+
*
50+
*/
51+
52+
#include <vector>
53+
using namespace std;
54+
55+
// @lc code=start
56+
class Solution {
57+
public:
58+
// 经典双指针
59+
void moveZeroes(vector<int> &nums) {
60+
int n = nums.size();
61+
if (n <= 1) {
62+
return;
63+
}
64+
int l = 0, r = 0; // l左侧全非0,lr之间全是0
65+
while (r < n) {
66+
// [0,1,0,3,12]
67+
if (nums[r] != 0) {
68+
swap(nums[l++], nums[r++]);
69+
} else {
70+
r++;
71+
}
72+
}
73+
}
74+
};
75+
// @lc code=end

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /