zoukankan      html  css  js  c++  java
  • 167. Two Sum II

    Problem:

    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.

    Note:

    Your returned answers (both index1 and index2) are not zero-based.
    You may assume that each input would have exactly one solution and you may not use the same element twice.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
    

    思路

    Solution (C++):

    vector<int> twoSum(vector<int>& numbers, int target) {
        int n = numbers.size();
        if (n < 2)  return vector<int>{};
        int i = 0, j = n-1;
        vector<int> res(2, 0);
        while (i < j) {
            if (numbers[i] + numbers[j] == target)  { res[0] = i+1; res[1] = j+1; break; }
            else if (numbers[i] + numbers[j] < target)  ++i;
            else if (numbers[i] + numbers[j] > target)  --j;
        }
        return res;
    }
    

    性能

    Runtime: 4 ms  Memory Usage: 7.3 MB

    思路

    Solution (C++):

    
    

    性能

    Runtime: ms  Memory Usage: MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    TCGA下载神器--TCGAbiolinks
    perl模块终极解决方案--转载
    Web前端优化
    关于CDN
    手写RateLimiter
    互联网高并发之限流
    互联网高并发之Hystrix实现服务隔离和降级
    关于Hystrix
    Apollo原理
    SpringBoot2.0之整合Apollo
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12640044.html
Copyright © 2011-2022 走看看