8000 update array.js · khemssharma/leetcode@262b1bb · GitHub
[go: up one dir, main page]

Skip to content

Commit 262b1bb

Browse files
committed
update array.js
1 parent c9a851c commit 262b1bb

File tree

1 file changed

+34
-10
lines changed

1 file changed

+34
-10
lines changed

array.js

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,28 +30,52 @@ var maxArea = function (height) {
3030
};
3131

3232
// trapping rain water
33-
var trap = function(height) {
33+
var trap = function (height) {
3434
if (height.length === 0) return 0;
3535
// two pointer and correspoding variables
36-
let left = 0, leftMax = 0;
37-
let right = height.length - 1, rightMax = 0;
36+
let left = 0,
37+
leftMax = 0;
38+
let right = height.length - 1,
39+
rightMax = 0;
3840
let waterTrapped = 0;
39-
while (left < right){
40-
if (height[left] < height[right]){
41-
if (height[left] >= leftMax){
41+
while (left < right) {
42+
if (height[left] < height[right]) {
43+
if (height[left] >= leftMax) {
4244
leftMax = height[left];
43-
}else{
45+
} else {
4446
waterTrapped += leftMax - height[left]
4547
}
4648
left++;
47-
}else{
48-
if (height[right] >= rightMax){
49+
} else {
50+
if (height[right] >= rightMax) {
4951
rightMax = height[right];
50-
}else{
52+
} else {
5153
waterTrapped += rightMax - height[right]
5254
}
5355
right--;
5456
}
5557
}
5658
return waterTrapped;
59+
};
60+
61+
// first missing positive
62+
var firstMissingPositive = function (nums) {
63+
let n = nums.length;
64+
// Place the numbers in thier correct position
65+
for (let i in nums) {
66+
// while the number is in range but not in correct position
67+
while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] !== nums[i]) {
68+
// swap number at i with its correct position
69+
let correctIndex = nums[i] - 1;
70+
[nums[i], nums[correctIndex]] = [nums[correctIndex], nums[i]]
71+
}
72+
}
73+
// Identify the first missing positive integer
74+
for (let i = 0; i < n; i++) {
75+
if (nums[i] !== i + 1) {
76+
return i + 1;
77+
}
78+
}
79+
// If all numbers are at their correct position return i+1
80+
return n + 1;
5781
};

0 commit comments

Comments
 (0)
0