当前位置: 移动技术网 > 科技>办公>内存 > LeetCode 1. 两数之和

LeetCode 1. 两数之和

2020年07月27日  | 移动技术网科技  | 我要评论

1.题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.解题

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0;i < nums.length;i ++) {
            if (hashMap.containsKey(target - nums[i])) {
                return new int[] {hashMap.get(target-nums[i]),i};
            }
            hashMap.put(nums[i],i);
        }
        throw new IllegalArgumentException("无");
    }
}

2ms 39.3MB


第一次看到这个题,是用暴力解写的,看了一下题解,恍然大悟,还是需要多加练习

题解点击此处

本文地址:https://blog.csdn.net/lolly1023/article/details/107597190

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网