码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Two Sum

时间:2015-08-12 21:32:25      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:

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

这里这样做的好处是可以处理多值重复的问题,你发现了没有。因为在map当中查找时,当前的值还没有放入map,如果是重复的,那也是没有影响的

[Leetcode] Two Sum

标签:

原文地址:http://www.cnblogs.com/deepblueme/p/4725440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!