Java beats 89.3%, nlog(n)


  • 1
    L

    public int[] twoSum(int[] nums, int target) {

         public int[] twoSum(int[] nums, int target) {   
         if(nums == null)return null;
    
        int len = nums.length;
        int[] arr = null;
        arr = java.util.Arrays.copyOf(nums, len);
    
        java.util.Arrays.sort(arr);
    
        int a = 0, b = 0;
    
        //find the two values
        int start = 0;
        int end = len-1;
        while(start < end){
            int sum = arr[start]+arr[end];
            if(target == sum){
                a = arr[start];
                b = arr[end];
                break;
            }
            if(target > sum){
                start++;
            }else if(target < sum){
                end--;
            }
        }
    
        //find the indexs of the two nums.
        int aa = 0;
        int bb = 0;
        boolean isAAssign = true;
        boolean isBAssign = true;
        for(int i = 0; i < len; i++){
            if(isAAssign && nums[i] == a){
                aa = i;
                isAAssign = false;
            }else if(isBAssign && nums[i] == b){
                bb = i;
                isBAssign = false;
            }
        }
    
        return new int[]{aa, bb};
    }

Log in to reply
 

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