zoukankan      html  css  js  c++  java
  • [leetCode][013] Two Sum 2

    题目:

    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

    题意:请首先看"[leetCode][012] Two Sum 1",大家发现什么异同了没(没发现的童鞋面壁去),这道题目仅仅更改了输入条件,Input的数组为已经排序的数组,并且呈现升序。输入条件变严格,我们依然可以使用前一篇问丈夫中的方法进行。那这里既然为升序,我们能不能不使用前一种方法而又能够达到O(n)时间复杂度呢? 答案是必然的。

    key Point:

      数组既然排序,元素之前的大小关系相对确定,存在的这一对元素必然处于相对固定的位置,我们可以使用两个游标,一个从头部遍历,一个从尾部遍历,两者所指元素之和如果偏大,调整后面的游标,相反则调整前面的游标。

    坑:

      由于两个int之和有可能出现INT_MAX的情况,所以如果输入类型给定int,则我们需要使用long long类型来表示才能避免出现溢出的情况。

    解答:

    以下为C++实现代码:

     1 class Solution{
     2 public:
     3         std::vector<int> twoSum(std::vector<int> &numbers, int target){
     4         std::vector<int> vecRet;
     5         int nLeft = 0;
     6         int nRight = numbers.size() - 1;
     7 
     8         while (nLeft < nRight){
     9             // 小心两个int之和溢出,使用long long类型
    10             long long int nAdd = numbers[nLeft] + numbers[nRight];
    11             if (nAdd == target){
    12                 vecRet.push_back(nLeft + 1);
    13                 vecRet.push_back(nRight + 1);
    14 
    15                 return vecRet;
    16             }
    17             else if (nAdd > target){
    18                 nRight--;
    19             }
    20             else if (nAdd < target){
    21                 nLeft++;
    22             }
    23         }
    24 
    25         return vecRet;
    26     } 
    27 };

    运行结果:

      

    希望各位看官不吝赐教,小弟感恩言谢。

  • 相关阅读:
    DFS
    关于memset

    SpringCloud(六)Ribbon负载均衡
    每日算法练习(2020-1-27)
    SpringCloud(五)Eureka Server高可用集群与常见问题
    SpringCloud(四)Eureka服务注册与发现
    SpringCloud(三)常用系统架构技术讲解
    Redis(八)
    Redis(七)
  • 原文地址:https://www.cnblogs.com/jiabei521/p/4227265.html
Copyright © 2011-2022 走看看