LeetCode TOP100 --- easy --- 01 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.
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法:
使用HashMap存储数组信息,由于需要判断数组值和目标值间的关系,将数组中元素值当作key,索引作为value。
在具体操作时可以先将数组信息放入哈希表,再遍历一遍从表内寻找,也可以在一次遍历中完成两部操作,代码使用第二种方法。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[] {-1,-1};
        }
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]),i};
            }
            map.put(nums[i], i);
        }
        return new int[] {-1,-1};
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务