Skip to content

Commit 8c8e4ca

Browse files
author
liguanliang1
committed
feat: fib & remove-duplicates
1 parent 3f1444e commit 8c8e4ca

File tree

3 files changed

+86
-1
lines changed

3 files changed

+86
-1
lines changed

leetcode/dynamic-programing/fib.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// 斐波那契数列
2+
// fib(n) = fib(n - 1) + fib(n - 2)
3+
4+
function fib(n) {
5+
let fibn_1 = 0
6+
let fibn_2 = 1
7+
if (n === 0) { return fibn_1 }
8+
if (n === 1) { return fibn_2 }
9+
10+
let i = 2
11+
let result = fibn_1 + fibn_2;
12+
while (i <= n) {
13+
result = fibn_1 + fibn_2;
14+
fibn_1 = fibn_2;
15+
fibn_2 = result;
16+
i++
17+
}
18+
19+
return result
20+
}
21+

leetcode/link-list/rotateList.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ function run() {
4444
}
4545

4646
const myRotateKGroup = () => {
47-
const n
47+
const n = 1;
4848
}
4949
const myReverse = (head, tail) => {
5050
let prev = tail.next;
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
2+
// 删除有序数组的重复项,不增加使用空间, 返回新数组长度
3+
4+
let removeDuplicates = (nums) => {
5+
// 解法1
6+
// if (nums.length <= 1) { return nums }
7+
8+
// let a = nums[0]
9+
// let b = nums[1];
10+
// index = 1;
11+
// while (b !== undefined) {
12+
// // 相邻两个数比较
13+
// if (a === b) { // 相等,原数组删除一个元素
14+
// nums.splice(index, 1)
15+
// b = nums[index]
16+
// } else { // 不相等,往前步进
17+
// a = nums[index]
18+
// b = nums[index + 1]
19+
// index++
20+
// }
21+
// }
22+
// return nums.length
23+
24+
25+
26+
27+
// map
28+
// if (nums.length <= 1) { return nums }
29+
30+
// let a = nums[0];
31+
// nums = nums.filter((value, index) => {
32+
// if (index === 0) {
33+
// return true
34+
// }
35+
// if (a === value) {
36+
// return false
37+
// } else {
38+
// a = value
39+
// return true
40+
// }
41+
// })
42+
// console.log(nums)
43+
// return nums.length
44+
45+
46+
// 官方解答
47+
const n = nums.length;
48+
if (n === 0) {
49+
return 0;
50+
}
51+
let fast = 1, slow = 1;
52+
while (fast < n) {
53+
if (nums[fast] !== nums[fast - 1]) {
54+
nums[slow] = nums[fast];
55+
++slow;
56+
}
57+
++fast;
58+
}
59+
return slow;
60+
}
61+
62+
63+
64+
removeDuplicates([1,1,2])

0 commit comments

Comments
 (0)