zoukankan      html  css  js  c++  java
  • LeetCode

    1.题目大意

    Given an array of integers that is already sorted in ascending order, 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

    给定一个已排序的整数数组numbers,找出其中两个相加能够等于target的数字。输出它们在数组里的序号。

    2.思路

    看了一下这道题的其它解题报告,有的写得太复杂了。普遍的第一个思路是两个for循环,这个思路是不大好的,时间复杂性是$O(n^2)$,数组稍微大一点的时候就会超时。第二个比较普遍思路是找target/2,以此为分界线,往前和往后判断,但这个方法其实也不是最好的。第三个思路就是接下来要说的,复杂性为$O(n)$的思路——从两端开始,分别记为i和j:

    (1)如果numbers[i]+numbers[j]的结果大于target的话就把j缩小,因为如果再把i增加,那么numbers[i]+numbers[j]结果就更大了。

    (2)如果numbers[i]+numbers[j]的结果小于target的话就把i增大,因为如果再把j减小,那么numbers[i]+numbers[j]结果就更小了。

    3.代码

    class Solution
    {
    public:
        vector<int> twoSum(vector<int>& numbers, int target)
        {
            int i=0,j=numbers.size()-1;
            while(i<j)
            {
                if(numbers[i]+numbers[j]==target)
                    return {i+1,j+1};
                else if(numbers[i]+numbers[j]>target)
                    j--;
                else if(numbers[i]+numbers[j]<target)
                    i++;
            }
            return  {0,0};
        }
    };
    

      

  • 相关阅读:
    MySql存储过程学习
    自己用C语言写的扫雷算法
    Spring学习——Hello World
    ICE Service使用方法简介
    DevExpress学习笔记(一)Ribbon
    DevExpress学习笔记(二)NavBarControl
    ORACLE DBLINK无法使用问题
    vbs脚本读写INI文件
    Python操作INI文件:configobj 更好
    个人发展的误区:越广越好,还是越深越好?
  • 原文地址:https://www.cnblogs.com/rgvb178/p/5966434.html
Copyright © 2011-2022 走看看