1. Two Sum

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.

(给定一组整数,将两个数的返回指数相加,使它们相加成一个特定的目标,您可以假设每个输入都有一个解决方案,您可能不会使用相同的元素两次)

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

我的解答结果:

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3        Map<Integer,Integer> map=new HashMap<>();
 4         for(int i=0;i<nums.length;i++){
 5             Integer index=map.get(target-nums[i]);
 6             if(null==index){
 7                 map.put(nums[i],i);
 8             }else{
 9                 return new int[]{index,i};
10             }
11         }
12         return null;
13     }
14 }

后满在评论区看到大神的解答结果,感觉很厉害,自己当时是没有想到的:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            Integer index=map.get(target-nums[i]);
            if(index==null){
                map.put(nums[i],i);
            }else{
                return new int[]{i,index};
            }
        }
        return new int[]{0,0};
    }
}

总结:

  第一种方法是大多数人都会想到的方法也是很简单的方法遍历数组,但是总觉得此方法太过笨重,从两个for循环就能看出来,因此在网上又找了下,看到第二种方法一下子还没看太懂,有点尴尬,仔细研究下,感觉这种方法好灵活,而且也不难看出此方法的效率是更高的。

posted @ 2017-12-16 17:35  lin拳拳  阅读(97)  评论(0)    收藏  举报