【LeetCode】 1.两数之和

题目:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。


示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


解题:

这题第一眼看就直接想到了暴力搜索,时间复杂度是O(n^2),但是会报超时。然后想到了先把数组快排一遍,再搜索,这样好像会快一点,但这知识错觉,时间复杂度还是O(n^2)。上网一搜,才知道居然还有这种操作:利用HashMap的特性,把时间复杂度缩减至O(n)。

大体思路是用空间换时间,将数组存在HashMap中,由于HashMap查找效率是常数级,所以能很快地找到结果。


代码:

import java.util.HashMap;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] rtn = new int[2];
        for (int i = 0 ; i < nums.length ; i++ ){
            if (map.containsKey(target-nums[i])){
                rtn[0] = map.get(target-nums[i]);
                rtn[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return rtn; 
    }
}

猜你喜欢

转载自blog.csdn.net/hhhhhsw/article/details/81039203