leetcode 1. Two Sum(两数之和)--题解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28635081/article/details/82807098

题目描述

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。


示例

给定  nums = [2, 7, 11, 15],target = 9

因为  nums[0] + nums[1] = 2 + 7 = 9

所以返回  [0, 1]


解题思路

最暴力的方法莫过于两层嵌套循环,原理简单,但效率太差;

这道题我的思路是使用哈希表,要是有更好方案的大佬轻喷。首先,创建存储结果的数组以便填充结果和哈希表用来做中间处理,然后开始遍历数组,先进行判断key中是否存在target - nums[i],如果不存在那么直接将当前的nums[i]及其索引i存入哈希表;如果存在,直接将target - nums[i]对应的value以及当前索引存入结果数组返回即可。


代码

public int[] twoSum(int[] nums, int target) {
    int[] result = new int[2];
    if (nums == null || nums.length < 2) return result;
    HashMap<Integer, Integer> hashMap = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (!hashMap.containsKey(target - nums[i])) hashMap.put(nums[i], i);
        else {
            result[0] = hashMap.get(target - nums[i]);
            result[1] = i;
        }
    }
    return result;
}

执行结果


欢迎各位大神指点

猜你喜欢

转载自blog.csdn.net/qq_28635081/article/details/82807098
今日推荐