leetcode (1) Two Sum js代码实现

港控/mmm° 2022-08-18 12:20 126阅读 0赞

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

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number[]}
  5. */
  6. var twoSum = function(nums, target) {
  7. var temp = nums.slice(0);
  8. nums = nums.sort(function(a,b){return a-b;});
  9. var i = 0;
  10. var j = nums.length - 1;
  11. while(nums[i] + nums[j] != target){
  12. if(nums[i] + nums[j] > target){
  13. j--;
  14. }else{
  15. i++;
  16. }
  17. }
  18. console.log(i);
  19. console.log(j);
  20. i = temp.indexOf(nums[i]);
  21. console.log(i);
  22. j = temp.lastIndexOf(nums[j]);
  23. i++;j++;
  24. var index = new Array(i, j);
  25. console.log(temp);
  26. console.log(nums);
  27. console.log(index);
  28. index = index.sort(function(a,b){return a-b;});
  29. return index;
  30. };

这道题目的主要思路:如果刚拿到题目的时候,可能想要会暴力穷举直接过了这道题,然而这样做性能太差无法通过,我们需要更加优秀的算法,那么就很容易想到现将给出的数组进行排序,从i=0和j=end开始计算两数相加之和,如果得到的sum大于目标值target,j向左移动,反之,i向右移动,这样的方法找到加数后再去原数组中找到两个数的数组下标就可以了

注意:这里用到深拷贝的方法,浅拷贝是引用,深拷贝是复制

同样也应该注意的是sort方法的意义

发表评论

表情:
评论列表 (有 0 条评论,126人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode1Two Sum

    本类型博客中的各算法的时间复杂度分析均为博主自己推算,本类型博客也是博主自己刷LeetCode的自己的一些总结,因此个中错误可能较多,非常欢迎各位大神在博客下方评论,请不吝赐教