Java Solution with Arrays.sort()


  • 0
    public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] oldNums=Arrays.copyOf(nums,nums.length);
        Arrays.sort(nums);
        int start=0,end=nums.length-1;
        while(start<end){
            int sum=nums[start]+nums[end];
             if(sum==target){
                break;
            }
            else if(sum<target) start++;
            else end--;
                
        }
        int a=nums[start];
        int b=nums[end];
        int[] res=new int[2];
        for(int i=0;i<nums.length;i++){
            if(a==oldNums[i]){
                 res[0]=i;
                 break;
            }
           
        }
        for(int j=0;j<nums.length;j++){
            if(b==oldNums[j]&&j!=res[0]){
                 res[1]=j;
                 break;
            }
           
        }
        return res;
    }
    

    }


Log in to reply
 

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