首页 > 其他 > 详细

[Leetcode] Two Sum

时间:2015-08-12 21:30:52      阅读:204      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!