Skip to content

Commit 4d1c861

Browse files
committed
22w6: add 283 js solution
1 parent c2d22b6 commit 4d1c861

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@
193193
|287|[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) | |Hard|
194194
|285|[Inorder Successor in BST](https://leetcode.com/problems/inorder-successor-in-bst/) ♥ | |Medium|
195195
|284|[Peeking Iterator](https://leetcode.com/problems/peeking-iterator/) | |Medium|
196-
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | |Easy|
196+
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/) | [js](./algorithms/moveZeroes/solution.js) |Easy|
197197
|282|[Expression Add Operators](https://leetcode.com/problems/expression-add-operators/) | |Hard|
198198
|279|[Perfect Squares](https://leetcode.com/problems/perfect-squares/) | |Medium|
199199
|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)| |Easy|

algorithms/moveZeroe/solution.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// 解法一:双循环,这是很笨的一种实现方式,时间复杂度也很高
2+
var moveZeroes = function(nums) {
3+
let x = 0;
4+
while(x < nums.length) {
5+
if(nums[x] === 0) {
6+
let y = x + 1;
7+
while (x < nums.length - 1 && y < nums.length - 1 && nums[y] === 0) {
8+
y++;
9+
}
10+
if (nums[y]) {
11+
[nums[x], nums[y]] = [nums[y], nums[x]]
12+
}
13+
}
14+
x++;
15+
}
16+
return nums;
17+
};
18+
19+
// 解法二:双循环的第二种解法
20+
var moveZeroes = function(nums) {
21+
let y = 0;
22+
// 第一次遍历的时候,y指针记录非0的个数,只要是非0的统统都赋给nums[y]
23+
for (let x = 0; x < nums.length; x++) {
24+
if(nums[x] !== 0) {
25+
nums[y++] = nums[x];
26+
}
27+
}
28+
// 非0元素统计完了,剩下的都是0了
29+
// 所以第二次遍历把末尾的元素都赋为0即可
30+
for (let x = y; x < nums.length; x++) {
31+
nums[x] = 0;
32+
}
33+
return nums;
34+
};
35+
36+
// 解法三:快排的思想(利用0,不等于0的都放到0的左边),达到一次循环
37+
var moveZeroes = function(nums) {
38+
let y = 0;
39+
for(let x = 0; x < nums.length; x++) {
40+
//当前元素!=0,就把其交换到左边,等于0的交换到右边
41+
if(nums[x] !== 0) {
42+
[nums[x], nums[y++]] = [nums[y], nums[x]];
43+
}
44+
}
45+
return nums;
46+
};

0 commit comments

Comments
 (0)