zoukankan      html  css  js  c++  java
  • 【数组】Two Sum

    题目:

    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

    思路:

      首先对数组排序。不过由于最后返回两个数字的索引,所以需要事先对数据进行备份。然后采用2个指针l和r,分别从左端和右端向中间运动:当l和r位置的两个数字之和小于目标数字target时,r减1;当l和r位置的两个数字之和大于目标数字target时,l加1。因此只需扫描一遍数组就可以检索出两个数字了。最后再扫描一遍原数组,获取这两个数字的索引。

     var twoSum = function(nums, target) {
                var temp=[];
                var index=[];
                for(var i=0;i<nums.length;i++){
                    temp[i]=nums[i];
                }
                temp.sort(function(a,b){return a-b;});
    
                var l=0,r=temp.length-1;
    
                while(l<r){
                    if(temp[l]+temp[r]==target){
                        break;
                    }else if(temp[l]+temp[r]>target){
                        r--;
                    }else{
                        l++;
                    }
                }
    
                for(var i=0,n=2;i<nums.length;i++){
                    if(nums[i]==temp[l]||nums[i]==temp[r]){
                        index.push(i+1);
                        --n;
                        if(n==0){
                            break;
                        }
                    }
                }
    
                return index;
            };
  • 相关阅读:
    并发编程之多线程理论
    僵尸进程和孤儿进程
    并发编程之多进程
    并发编程之多进程理论
    操作系统介绍
    面向对象和网络编程练习题
    网络编程——socket编程
    面向对象练习题
    面向对象软件开发实战
    异常处理
  • 原文地址:https://www.cnblogs.com/shytong/p/5099382.html
Copyright © 2011-2022 走看看