techiall / Blog

🍋 [My Blog] See discussions
https://github.com/techiall/Blog/discussions
MIT License
8 stars 1 forks source link

Leetcode | 两数之和 #8

Open techiall opened 6 years ago

techiall commented 6 years ago

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

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

示例:

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

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

c++

利用哈希,先判断相减后的值是否存在,不存在的话将该数组中的值作为主键,存入哈希中,之后匹配。

查找成功则返回。

若找不到索引,find() 的返回值为 .end()。

class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            map<int, int> hash_map;
            vector<int> re;
            for (size_t i = 0; i < nums.size(); i++) {
                int tmp = target - nums[i];
                if (hash_map.find(tmp) != hash_map.end()) {
                    re.push_back(hash_map[target - nums[i]]);
                    re.push_back(i);
                    break;
                }
                hash_map[nums[i]] = i;
            }
            return re;
        }
};

Java

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