Skip to content

Commit 5419d4f

Browse files
updated canJump
1 parent d7a4c5e commit 5419d4f

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

exercises/leetcode/google/canJump.js

+36
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,25 @@
1+
/**
2+
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
3+
4+
Each element in the array represents your maximum jump length at that position.
5+
6+
Determine if you are able to reach the last index.
7+
8+
Example 1:
9+
10+
Input: [2,3,1,1,4]
11+
Output: true
12+
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
13+
Example 2:
14+
15+
Input: [3,2,1,0,4]
16+
Output: false
17+
Explanation: You will always arrive at index 3 no matter what. Its maximum
18+
jump length is 0, which makes it impossible to reach the last index.
19+
*/
20+
21+
// O(n2) : Time Complexity
22+
// O(n) : Space Complexity
123
const INDEX = {
224
'G': 'GOOD',
325
'B': 'BAD',
@@ -22,4 +44,18 @@ const canJump = nums => {
2244
}
2345

2446
return map[0] == INDEX.G;
47+
}
48+
49+
// Greedy Approach
50+
51+
const canJump = nums => {
52+
let lastPos = nums.length - 1;
53+
54+
for (let i = nums.length - 1; i >= 0; i--) {
55+
if (i + nums[i] >= lastPos) {
56+
lastPos = i;
57+
}
58+
}
59+
60+
return lastPos == 0;
2561
}

exercises/leetcode/sortColors.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent,
3+
* with the colors in the order red, white and blue.
4+
5+
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
6+
7+
Note: You are not suppose to use the library's sort function for this problem.
8+
9+
Example:
10+
11+
Input: [2,0,2,1,1,0]
12+
Output: [0,0,1,1,2,2]
13+
Follow up:
14+
15+
A rather straight forward solution is a two-pass algorithm using counting sort.
16+
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
17+
Could you come up with a one-pass algorithm using only constant space?
18+
*/
19+
20+
const sortColors = nums => {
21+
let p0 = 0;
22+
let curr = 0;
23+
let p2 = nums.length - 1;
24+
25+
while (curr <= p2) {
26+
if (nums[curr] === 0) {
27+
[nums[curr], nums[p0]] = [nums[p0], nums[curr]];
28+
curr++;
29+
p0++;
30+
} else if (nums[curr] === 2) {
31+
[nums[curr], nums[p2]] = [nums[p2], nums[curr]];
32+
p2--;
33+
} else {
34+
curr++;
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)