My java solution


  • -3
    H
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] arr = new int[numbers.length];
            for(int k = 0; k < numbers.length; k++){
                arr[k] = numbers[k];
            }
            Arrays.sort(numbers);
            int[] res = new int[2];
            int i, j;
            for(i = 0, j = numbers.length - 1; i < j;){
                if(numbers[i] + numbers[j] == target) break;
                else if(numbers[i] + numbers[j] > target) j--;
                else i++;
            }
            int m, n;
            for(m = 0; m < arr.length; m++){
                if(arr[m] == numbers[i]) break;
            }
            for(n = 0; n < arr.length; n++){
                if(arr[n] == numbers[j] && n != m) break;
            }
            res[0] = Math.min(m+1,n+1);
            res[1] = Math.max(m+1,n+1);
            return res;
        }
    }

  • 0
    B

    just some advise~, you needed another O(n) space to put the sorted array and,using binary search to find the element ? It still need O(nlgn) time . I think it is not a good idea , there might be O(n) solution.


Log in to reply
 

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