simple version of 3sum


  • 0

    public class Solution {

    public int[] twoSum(int[] numbers, int target) {
        if (numbers == null || numbers.length == 0 || numbers[0] > target) { return null; }
        //find last number that is no bigger than target.
        int end = numbers.length - 1;
        for(int i = 0; i < numbers.length; i++) {
            if(numbers[i] > target) { return null; }
            
            while(i < end && numbers[i] + numbers[end] > target) {
                end --;
            }
            
            int currSum = numbers[i] + numbers[end];
            if(currSum == target) {
                return new int[]{i+1, end+1};
            } else {
                if(end < numbers.length - 1) {
                    end++;
                }
            }
        }
        
        return null;
    }
    

    }


Log in to reply
 

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