SHARE
TWEET

Untitled

a guest Jan 24th, 2020 58 in 4 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var arr = [-1, 0, 1, 1, 2, 3, 5, 6, 7, 8, 9, 1, 5]
  2. var sum = 6
  3.  
  4.  
  5. function doIt(arr, sum) {
  6.   var hashMap = {};
  7.   var result = [];
  8.   arr.forEach(v => {
  9.     if (hashMap[v]) {
  10.       hashMap[v]++;
  11.     } else {
  12.       hashMap[v] = 1;
  13.     }
  14.   });
  15.   arr.forEach(v => {
  16.     if (hashMap[sum - v] && hashMap[v]) {
  17.       const diff = sum - v;
  18.       if (!(diff === v && hashMap[v] < 2)) {
  19.         result.push([v, sum - v]);
  20.         hashMap[v] = 0;
  21.       }
  22.     }
  23.   })
  24.   return result;
  25. }
  26.  
  27. console.log(doIt(arr, sum)) // [[-1, 7], [0,6], [1,5]]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top