Java Code Beats 90%


  • 0
    S
    public static int[] twoSum(int[] nums, int target){
        int[] result = {0,0};
        int[] copy = new int[nums.length];
        System.arraycopy(nums, 0, copy, 0, nums.length);
        Arrays.sort(nums);
        //Sort and find the largest match number
        while(result[1]<nums.length-1&&nums[result[1]]+nums[0]<target){
            result[1]++;
        }
        while(result[0]<result[1]){
            while(result[0]<result[1]&&nums[result[0]]+nums[result[1]]>target){
                result[1]--;
            }
            while(result[0]<result[1]&&nums[result[0]]+nums[result[1]]<target){
                result[0]++;
            }
            if(nums[result[0]]+nums[result[1]]==target){
                break;
            }
        }
        int i;
        for(i=0;i<nums.length&&copy[i]!=nums[result[0]];i++){}
        result[0]=i;
        for(i=nums.length-1;i>=0&&copy[i]!=nums[result[1]];i--){}
        result[1]=i;
        return result;
        
    }

Log in to reply
 

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