[leetcode]1.Two Sum

题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法一

思路

看到这道题,我的第一个思路就是用两个for循环来解,这样的话时间复杂度为O(n2),解法很简单,但是不是最优解。

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        A:
        for(int i = 0; i < nums.length; i++) {
            for(int j = i+1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    break A;
                }
            }
        }
        return result;
    }
}

解法二

思路

认真看了讨论区,学习到了用HashMap来解题,由于对HashMap不是很熟悉,所以去学习了HashMap的相关知识,发现用HashMap的查找时间复杂度接近为O(1),所以现在我们只用一个for循环就可以实现算法,时间复杂度接近O(n)。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(hash.containsKey(target - nums[i])) {
                result[0] = hash.get(target - nums[i]);
                result[1] = i;    //这里注意result[0]和result[1]的值不要写反
                break;
            }
            hash.put(nums[i], i);
        }
        return result;
    }
}

补充:HashMap的相关知识

HashMap底层是通过数组加链表来实现的。如下图所示:

当查询一个键值对的时候,实际上一共进行了四步:
1.先根据key值计算出hash值,然后经过h&(length-1)得到index值
2.查找数组中的index位置,得到相应位置的键值对表
3.根据key值,遍历链表,找到相应的键值对。
4.从键值对中取出value值。

其中1,2,4的时间复杂度均为O(1),而3只在理想情况下可以在O(1)时间下完成,“冲突”越少,即数组每个index的链表越短,查找效率就越快。

更多的HashMap底层的相关知识可参考:Java集合:HashMap源码剖析

posted @ 2018-09-28 11:20  shinjia  阅读(83)  评论(0编辑  收藏  举报