The third solution O(nlogn) 5ms in Java


  • 0
    P
    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] res = new int[2];
            if(nums == null || nums.length == 0)
                return res;
            int[] nums2 = Arrays.copyOf(nums, nums.length);
            Arrays.sort(nums2);
            int start = 0;
            int end = nums.length - 1;
            while(start < end) {
                if(nums2[start] + nums2[end] == target) {
                    break;
                } else if(nums2[start] + nums2[end] < target)
                        start++;
                else end--;
            }
            int count = 0;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] == nums2[start] && count == 0) {
                    res[0] = i;
                    count = 1;
                }
                if(nums[i] == nums2[end])
                    res[1] = i;
            }
            return res;
        }
    }

Log in to reply
 

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