两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。



给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]


 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
 4         int[] res = new int[2];
 5         for (int i = 0; i < nums.length; i++) {
 6             if (m.containsKey(target - nums[i])) {
 7                 res[0] = i;
 8                 res[1] = m.get(target - nums[i]);
 9                 break;
10                 
11             }
12             m.put(nums[i], i);
13         }
14         return res;
15         
16     }
17 }

 


 

posted @ 2019-03-30 10:29  Doraon  阅读(78)  评论(0)    收藏  举报