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};
        }
    };
    

      

  • 相关阅读:
    (转)关于c#中的事件
    MySql数据库--持续记录ing
    在Eclipse中通过JDBC连接MySQL步骤,非常详细!
    mybatis传入参数类型parameterType和输出结果类型resultType详解
    关于JDBC访问存储过程的问题
    Mybatis(一)入门
    [Redis] 基于redis的分布式锁
    分布式锁----浅析redis实现
    MyBatis的增删改查操作
    C3P0连接池工具类实现步骤及方法
  • 原文地址:https://www.cnblogs.com/rgvb178/p/5966434.html
Copyright © 2011-2022 走看看