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

[LC]1 Two Sum

时间:2017-08-29 12:33:09      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:use   current   int   numbers   two sum   logs   element   ice   input   

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].






思路一:两个for loop,干掉,千万别用。
思路二:用map先loop一遍存起来,然后再loop一遍数组,看target-current这个差值存不存在map里。
思路二优化:把两次loop合并成一次loop:
       public int[] twoSum(int[] nums, int target){
         int[] res = new int[2];
         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
         for(int i=0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])){
                res[1]=map.get(target-nums[i]);
                res[2]=i;
                return res;
            }
            map.put(nums[i],i);
        }

        return res;
     }

 



 



  

[LC]1 Two Sum

标签:use   current   int   numbers   two sum   logs   element   ice   input   

原文地址:http://www.cnblogs.com/mandyliu/p/7447117.html

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