LeetCode 1. 两数之和 Two Sum

题目描述

给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。

您可以假设每个输入都只有一个解决方案,并且您不会使用元素两次。

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路与实现

使用查找表 O(n) O (n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hash = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hash.containsKey(target - nums[i])) {
                int j = hash.get(target - nums[i]);
                return new int[]{j, i};
            } else {
                hash.put(nums[i], i);
            }
        }
        return null;
    }
}
posted @ 2019-08-14 10:13  丶沧月  阅读(116)  评论(0)    收藏  举报