leetcode1~Two Sum

来源:互联网 发布:word2003软件官方下载 编辑:程序博客网 时间:2024/06/12 23:46

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.

使用哈希表。
键存储对应的元素,值存储下标。因为返回的是下标,所以要通过键取值。
由于数组中的元素可能会有重复,故一开始时不可以将数组的元素直接存储到哈希表中。

public class TwoSum {    public int[] twoSum(int[] nums, int target) {        int[] res = new int[2];        Map<Integer,Integer> map = new HashMap<>();        for(int i=0;i<nums.length;i++) {            if(map.containsKey(target-nums[i])) {                res[1] = i;  //i在后面                res[0] = map.get(target-nums[i]);            } else {                map.put(nums[i],i);            }        }        return res;    }}
0 0