leetcode 1. Two Sum

来源:互联网 发布:淘宝的全球购是正品吗 编辑:程序博客网 时间:2024/04/29 16:46
原题链接:1. Two Sum

【思路1-Java】

借用 hashmap,时间复杂度可以降到 O(n),hashmap 中 key 为 nums 数组元素的值,value 为数组元素对应下标。假如对于第 i 个数 nums[i],如果 hashmap 中包含 target - nums[i]的  key 值,那么说明已经可以找到这样两个和为 target 的数,返回即可,否则,返回 null:

    public int[] twoSum(int[] nums, int target) {        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();        for (int i = 0; i < nums.length; i++)            if (hm.containsKey(target - nums[i])) return new int[]{hm.get(target - nums[i]), i};            else hm.put(nums[i], i);        return null;    }
16 / 16 test cases passed. Runtime: 6 ms  Your runtime beats 58.79% of javasubmissions.
【思路2-Java】
 如果不借用 hashmap,直接用 brute force的话,时间复杂度为 O(n2)。我们可以先对 nums 数组进行排序,时间复杂度为O(nlogn),然后用两个指针start 和 end分别指向开头和结尾,在 start < end 范围内进行查找,有下列3中情况:

1. nums[start] + nums[end] = target,那么直接返回 start 和 end

2. nums[start] + nums[end] < target,那么 start++

3. nums[start] + nums[end] > target,那么 end--

如果没找到就返回 null。

但是我们要注意的是,不能直接对原数组进行排序,因为原数组被打乱了,那么原先的下标也就被打乱了,正确的做法是:申请一个同样大小的数组,然后将原数组拷贝到新的数组中,再对新数组进行排序,最后在原数组中找到这两个元素的下标即可:

    public int[] twoSum(int[] nums, int target) {        int[] sNums = new int[nums.length], res = null;        System.arraycopy(nums,0,sNums,0,nums.length);        Arrays.sort(sNums);        int start = 0, end = nums.length - 1, index = 0;        while(start < end)            if (sNums[start] + sNums[end] == target) {res = new int[]{start, end}; break;}            else if (sNums[start] + sNums[end] < target) start++;            else end--;        for (int i = 0; i < nums.length; i++)            if (sNums[start] == nums[i] || sNums[end] == nums[i]) res[index++] = i;        return res;    }
16 / 16 test cases passed. Runtime: 4 ms  Your runtime beats 98.85% of javasubmissions.

欢迎优化!


1 0
原创粉丝点击