首页 > 其他 > 详细

TwoSum leetcode

时间:2015-12-08 00:05:18      阅读:232      评论:0      收藏:0      [点我收藏+]

刚刚用两小时刷了leetcode的第一题

 

题目如下:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

我的答案如下:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var obj = {};
    var samekey = {};
    nums.filter(function(ele,index){
           if(obj[ele]) samekey[ele]= index+1;
           else obj[ele] = index+1;
    });
    for(var i in obj){
        if(nums.indexOf((target-i)) !== -1){
            if(samekey[target-i]){
                return [obj[i],samekey[target-i]];
            }
            if(obj[target-i]){
                return obj[i] > obj[target-i] ? [obj[target-i],obj[i]] : [obj[i],obj[target-i]];
            } 
        }
    }
};

  这个按道理来说复杂度也是o(n*n);但是因为有一层过滤相同的数据项,n的数量要比实际的数量少一些,速度稍微快点。平均速度在160ms左右

直接遍历的答案如下: 速度在700ms以上

var twoSum = function(nums, target) {
   for(var i=0;i<nums.length;i++){
       var find = target - nums[i];
       var tmp = nums[i];
       nums[i] = null;
       var finder = nums.indexOf(find);
       if(  finder !== -1){
           return finder > i ? [i+1,finder+1] : [finder+1,i+1];
       }
       nums[i] = tmp;
   }
    
    
};

  

 

TwoSum leetcode

原文:http://www.cnblogs.com/kooais/p/5027704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!