Clean, easy to understand solution in Java


  • 0
    T
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int len = numbers.length;
            
            int i = 0;
            int j = len - 1;
            
            while (i < j) {
                int sum = numbers[i] + numbers[j];
                
                if (sum > target) j--;
                else if (sum < target) i++;
                else return new int[] {i+1, j+1};
            }
            return new int[] {-1, -1}; // never comes here if sum exists
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.