Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active November 4, 2017 01:11
Show Gist options
  • Save jialinhuang00/c4a7a62254648881f11a3afecb0e2bc8 to your computer and use it in GitHub Desktop.
Save jialinhuang00/c4a7a62254648881f11a3afecb0e2bc8 to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
1.pair off for the required parameter 'sum'.
2.the former by myself is using two loops
3.two ways turned out to be different.
the reference used at the second function is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch
-----------------------------------------------------------------------------*/
function twoSum(numArr, sum) {
// scrutinize every element
// i cannot be paired itself off so i !==j
var arrpair = [];
for (var i = 0; i < numArr.length; i++) {
for (var j = numArr.length - 1; j > i; j--) {
if (j !== i && numArr[i] + numArr[j] === sum) {
arrpair.push([numArr[i], numArr[j]]);
}
}
}
return arrpair;
}
twoSum([1,6,4,5,3,3],7);
// [ [ 1, 6 ], [ 4, 3 ], [ 4, 3 ] ]
// ----------------------------------------
function twoSum2(numArr, sum){
var pairs=[], hashtable =[];
for(var i=0; i<numArr.length;i++){
var currNum = numArr[i];
var counterNum = sum - numArr[i];
if(hashtable.indexOf(counterNum) > -1){
pairs.push([currNum, counterNum]);
}
hashtable.push(currNum);
}
return pairs;
}
twoSum2([1,6,4,5,3,3],7);
// [ [ 6, 1 ], [ 3, 4 ], [ 3, 4 ] ]
// Remember to return the smaller sum if multiple are possible.
// This means ([1,1,1], 2) should use 0 + 1 instead of 0 + 2 & 1 + 2.
function pairwiseRefactored2(arr, arg) {
var sum = 0, pairArr = arr.slice(), len = pairArr.length, i, j;
for(i = 0; i < len; i++) {
for(j = i + 1; j < len; j++) {
if(pairArr[i] + pairArr[j] == arg) {
// Plus every element's index that can match the other
sum += i + j;
// Set the indices to NaN so that they can't be used in next iteration
pairArr[i] = pairArr[j] = NaN;
break;
}
}
}
return sum;
}
var twoSum = function(nums, target) {
var match=[];
for (var i = 0; i < nums.length; i++) {
for (var j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]) {
match.push(i,j);
return match;
}
}
}
};
twoSum([3, 2, 4], 6); // [1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment