1. Two Sum

1. 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.

Example:

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

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

分析:题目的要求是给出一个数组以及一个数target,找到该数组中哪两个数的和是target,返回一个存储这两个数索引的数组。

  1. 常规暴力搜索,在LeetCode是可以通过的。
  2. 要缩短时间,用空间换时间,使用一个HashMap,key存储数组值,value存储对应的索引值。遍历一次数组,每次首先检查target - nums[i]是否在map中,如果不在则将该数以及对象索引加入map,否则就找到了这两个索引了。
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = {-1, -1};
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])){
                ans[0] = map.get(target - nums[i]);
                ans[1] = i;
            }else {
                map.put(nums[i], i);
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/zhuobo/p/10749960.html