fueanta

LeetCode 167: Two Sum II - Input array is sorted

Jun 30th, 2021
728
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function twoSum(numbers: number[], target: number): number[] {
  2.     let i = 0;
  3.     let j = numbers.length - 1;
  4.    
  5.     const answers: number[] = [];
  6.    
  7.     while (i < j) {
  8.         const sum = numbers[i] + numbers[j];
  9.        
  10.         if (sum === target) {
  11.             answers.push(++i, ++j);
  12.             break;
  13.         }
  14.         else if (sum > target) j--;
  15.         else i++;
  16.     }
  17.    
  18.     return answers;
  19. };
RAW Paste Data