Skip to content

Commit a1685a6

Browse files
authored
Merge pull request #1169 from lhc0506/main
[lhc0506] WEEK 1 solutions
2 parents 548e4cc + a6a966b commit a1685a6

File tree

5 files changed

+92
-0
lines changed

5 files changed

+92
-0
lines changed

contains-duplicate/lhc0506.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {boolean}
4+
*/
5+
var containsDuplicate = function(nums) {
6+
const numsSet = new Set();
7+
nums.forEach(num => numsSet.add(num));
8+
9+
return nums.length !== numsSet.size;
10+
};

house-robber/lhc0506.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var rob = function(nums) {
6+
if (nums.length < 2) {
7+
return Math.max(nums);
8+
}
9+
10+
let twoBefore = 0;
11+
let oneBefore = 0;
12+
13+
nums.forEach(num => {
14+
const prevOneBefore = oneBefore;
15+
oneBefore = Math.max(prevOneBefore, twoBefore + num);
16+
twoBefore = prevOneBefore;
17+
});
18+
19+
return Math.max(oneBefore, twoBefore);
20+
};
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
var longestConsecutive = function(nums) {
7+
const numSet = new Set(nums);
8+
9+
let maxLength = 0;
10+
let currentLength = 0;
11+
12+
const countConsecutive = (num, step) => {
13+
let currentNum = num;
14+
while(numSet.has(currentNum)) {
15+
numSet.delete(currentNum);
16+
currentNum += step;
17+
currentLength += 1;
18+
}
19+
}
20+
21+
nums.forEach(num => {
22+
countConsecutive(num, 1);
23+
countConsecutive(num - 1, -1);
24+
25+
maxLength = Math.max(maxLength, currentLength);
26+
currentLength = 0;
27+
});
28+
29+
return maxLength;
30+
};

top-k-frequent-elements/lhc0506.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var topKFrequent = function(nums, k) {
7+
const numsMap = {};
8+
9+
nums.forEach(num => {
10+
numsMap[num] ? numsMap[num] += 1 : numsMap[num] = 1;
11+
});
12+
13+
return Object.entries(numsMap).sort((a, b) => b[1] - a[1]).slice(0, k).map(([key]) => Number(key));
14+
};

two-sum/lhc0506.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var twoSum = function(nums, target) {
7+
const numsMap = {};
8+
9+
for (let i = 0; i < nums.length; i++) {
10+
const needNum = target - nums[i];
11+
12+
if (needNum in numsMap) {
13+
return [i, numsMap[needNum]];
14+
}
15+
16+
numsMap[nums[i]] = i;
17+
}
18+
};

0 commit comments

Comments
 (0)