1. two Sum

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 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number[]}
 5  */
 6 var twoSum = function(nums, target) {
 7      var hash = {},len = nums.length;
 8     
 9     //其实这里是有重复的值可能性的,比如[3,3],那第二个会覆盖第一个
10     for(var i = 0;i < len;i++){
11         
12         hash[nums[i]] = i;
13     }
14     
15     
16     //由于题目说过有且只有一组解,所以上面覆盖也没关系,因为我们只找后面一个可行解。
17     for(var j = 0;j < len;j++){
18         if(hash[target - nums[j]]){
19             return [j,hash[target - nums[j]]];
20         }
21     }
22 };
 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number[]}
 5  */
 6 var twoSum = function(nums, target) {
 7   
 8     //双指针,思路就是先排序,两边向中间靠拢
 9     var old = nums.slice(),
10         len = old.length,
11         i = 0,
12         j = len -1;
13     nums.sort();
14     while(i<len&&j > -1){
15         
16         var temp = nums[i] + nums[j];
17         if(temp === target){
18             var fir = old.indexOf(nums[i]);
19             //这里要防止重复[3,3]求6
20             
21             var sec = old.lastIndexOf(nums[j])
22             return [fir,sec];
23         }
24         
25         if(temp < target){
26             i++;
27         }else{
28             j--;
29         }
30     }
31     
32 };

 

 

 
posted @ 2017-10-05 20:45  hdu胡恩超  阅读(148)  评论(0编辑  收藏  举报