Skip to content

Commit a7115fb

Browse files
author
hjzheng
committed
2020-03-11
1 parent 1ce29f9 commit a7115fb

File tree

3 files changed

+121
-0
lines changed

3 files changed

+121
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* @lc app=leetcode.cn id=1013 lang=javascript
3+
*
4+
* [1013] 将数组分成和相等的三个部分
5+
*/
6+
7+
// @lc code=start
8+
/**
9+
* @param {number[]} A
10+
* @return {boolean}
11+
*/
12+
/**
13+
* @param {number[]} A
14+
* @return {boolean}
15+
*/
16+
var canThreePartsEqualSum = function(A) {
17+
// 求和
18+
let sum = A.reduce((sum, n) => (sum += n), 0);
19+
20+
if (sum % 3 !== 0) {
21+
return false;
22+
}
23+
24+
const avg = sum / 3;
25+
26+
// 左右指针,left right 初始化不为 0 的情况,是有可能 avg 可能是 0
27+
let left = null,
28+
right = null,
29+
i = 0,
30+
j = A.length - 1;
31+
32+
// j - i > 1 必须分成3份,所以中间至少得有一个元素
33+
while (j - i > 1) {
34+
if (left !== avg) {
35+
left = left === null ? 0 : left;
36+
left += A[i];
37+
// 已经等于平均值的话,索引就不更新了
38+
left !== avg && (i += 1);
39+
}
40+
41+
if (right !== avg) {
42+
right = right === null ? 0 : right;
43+
right += A[j];
44+
45+
// 已经等于平均值的话,索引就不更新了
46+
right !== avg && (j -= 1);
47+
}
48+
49+
if (left === avg && right === avg) {
50+
return true;
51+
}
52+
}
53+
54+
return false;
55+
};
56+
// @lc code=end

35.搜索插入位置.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* @lc app=leetcode.cn id=35 lang=javascript
3+
*
4+
* [35] 搜索插入位置
5+
*/
6+
7+
// @lc code=start
8+
/**
9+
* @param {number[]} nums
10+
* @param {number} target
11+
* @return {number}
12+
*/
13+
/**
14+
* @param {number[]} nums
15+
* @param {number} target
16+
* @return {number}
17+
*/
18+
/* 二分查找 */
19+
var searchInsert = function(nums, target) {
20+
let left = 0,
21+
right = nums.length - 1,
22+
mid = null;
23+
24+
while (right >= left) {
25+
let mid = Math.floor((right + left) / 2);
26+
if (nums[mid] === target) {
27+
return mid;
28+
} else if (nums[mid] > target) {
29+
right = mid - 1;
30+
} else {
31+
left = mid + 1;
32+
}
33+
}
34+
35+
return left;
36+
};
37+
// @lc code=end

89.格雷编码.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* @lc app=leetcode.cn id=89 lang=javascript
3+
*
4+
* [89] 格雷编码
5+
*/
6+
7+
// @lc code=start
8+
/**
9+
* @param {number} n
10+
* @return {number[]}
11+
*/
12+
var grayCode = function(n) {
13+
if (n === 0) {
14+
return [0];
15+
}
16+
17+
if (n === 1) {
18+
return [0, 1];
19+
}
20+
21+
let preGrayCode = grayCode(n - 1);
22+
23+
return [
24+
...preGrayCode,
25+
...preGrayCode.reverse().map(v => v + Math.pow(2, n - 1))
26+
];
27+
};
28+
// @lc code=end

0 commit comments

Comments
 (0)