Using Two pointers, nlogn Java solution


  • 0
    Z
        public int[] twoSum(int[] nums, int target) {
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            for(int i=0;i<nums.length;i++) tmp.add(i);
            Collections.sort(tmp,(i,j) -> (nums[i] - nums[j]));
            int[] res = new int[2];
            for(int i=0,j=nums.length-1;i<j;) {
                int sum = nums[tmp.get(i)] + nums[tmp.get(j)];
                if(sum == target) {
                    res[0] = tmp.get(i);
                    res[1] = tmp.get(j);
                    return res;
                }else if(sum < target){
                    i++;
                }else {
                    j--;
                }
            }
            return res;
        }
    

Log in to reply
 

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