Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 08a7322

Browse files
authored
Update 15. 3Sum.js
1 parent 32499b8 commit 08a7322

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

‎11-20/15. 3Sum.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,42 @@
11
var threeSum = function(nums) {
2+
// Create array a to store output array
23
let a = []
4+
// Create variable j and k for indexing nums[j] and nums[k]
5+
// Create val1 and val2 for storing value of nums[j] and nums[k] respectively
36
let [j,k,val1,val2] = [0,0,0,0]
7+
// sort the input array ascendingly
48
nums.sort(function(a,b){return a-b})
5-
for(let i = 0 ;i < nums.length-2;i++){
9+
// run loop over nums from (0,nums.length-2)
10+
// we need i , j , k so last usable index of will be nums.length-2
11+
// storing length helps a little bit for optimization
12+
len = nums.length
13+
for(let i = 0 ;i < len-2;i++){
14+
// nums[i] must be negative or 0 to get nums[i] + nums[j] + nums[k] == 0
615
if(nums[i] > 0 ){continue}
16+
// we will cover all possible triplet for nums[i] so we dont need to rerun for same value
717
if(nums[i] == nums[i-1]){continue}
18+
// j will be the start pointer and k will be end pointer for our window
819
j = 1 + i
9-
k = nums.length - 1
20+
k = len - 1
21+
// we will run this until the whole window is convered
1022
while(j < k ){
1123
if(nums[i] + nums[j] + nums[k] == 0){
24+
// if this condition is met we add it to answer array
1225
a.push([nums[i] , nums[j] , nums[k]])
26+
// we store value of nums[j] in val1
1327
val1=nums[j];
28+
// we skip all index with same value as nums[j] this will help up shorten the window
1429
while(j<k && nums[j]==val1) j++;
1530
val2=nums[k];
31+
// we skip all index with same value as nums[k] this will help up shorten the window
1632
while(j<k && nums[k]==val2) k--;
17-
}else if(nums[i]+nums[j]+nums[k]<0) j++;
33+
// if total is < 0 we try to get a greater value for nums[j] (array is sorted ascending)
34+
}else if(nums[i]+nums[j]+nums[k]<0) j++;
35+
// if total is > 0 we try to get a smaller value for nums[k] (array is sorted ascending)
1836
else if(nums[i]+nums[j]+nums[k]>0) k--;
37+
// thus when this loop is done we will have all possible j and k for given nums[i]
1938
}
2039
}
40+
// return the output array
2141
return a
22-
};
42+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /