F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

[Leetcode] Two Sum

 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,如果是重复的,那也是没有影响的

posted on 2015-08-12 20:12  F_G  阅读(166)  评论(0编辑  收藏  举报