LeetCode 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 sameelement twice.

Example:

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

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

 

 1 /*
 2     思路:
 3     目标就是要找满足nums[current] + nums[another] == target,且current!=another的current和another
 4     为了快速的定位另一个加数,可以使用map。map的key是要查找的加数,value是该加数对应的位置。
 5     而map的确定和查找正好可以同步确定。故遍历一遍nums就可以解决问题。
 6      */
 7     public int[] twoSum(int[] nums, int target) {
 8         int[] result = new int[2];
 9         Map<Integer, Integer> map = new HashMap<>();
10         for (int i = 0; i < nums.length; i++) {
11             int another = target - nums[i];
12 
13             Integer indice = map.get(another);
14             if (indice != null) {
15                 if (indice != i) {
16                     result[0] = i;
17                     result[1] = indice;
18                     return result;
19                 }
20             }else{
21                 map.put(nums[i], i);
22             }
23         }
24         return result;
25     }
26 //    暴力方法
27 //    public int[] twoSum(int[] nums, int target) {
28 //        int[] result = new int[2];
29 //        for (int low = 0; low < nums.length - 1; low++) {
30 //            for (int high = nums.length - 1; high > low; high--) {
31 //                if (nums[low] + nums[high] == target){
32 //                    result[0] = low;
33 //                    result[1] = high;
34 //                    return result;
35 //                }
36 //            }
37 //        }
38 //        return result;
39 //    }

 

posted @ 2019-05-19 15:15  赤云封天  阅读(110)  评论(0编辑  收藏  举报