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

    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 and you may not use the same element twice.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    Subscribe to see which companies asked this question.

     1 #include<iostream>
     2 #include<vector>
     3 #include<algorithm>
     4 using namespace std;
     5 class Solution {
     6 public:
     7     vector<int> twoSum(vector<int>& numbers, int target) {
     8         vector<int> v;
     9         int begin = 0;
    10         int end = numbers.size() - 1;
    11         
    12         while (begin<end)
    13         {
    14             if ((numbers[begin] + numbers[end]) == target)
    15             {
    16                 v.push_back(begin + 1);
    17                 v.push_back(end + 1);
    18                 break;
    19             }
    20             else
    21             if ((numbers[begin] + numbers[end])>target)
    22             {
    23                 end--;
    24             }
    25             else
    26                 begin++;
    27         }
    28         return v;
    29     }
    30 };
    31 int main()
    32 {
    33     vector<int> v{ 2, 7, 11, 15 };
    34     int target = 9;
    35     vector<int> v1;
    36     Solution s;
    37     v1 = s.twoSum(v, target);
    38     for (auto a : v1)
    39         cout << a << " ";
    40     system("pause");
    41     return 0;
    42 }
  • 相关阅读:
    淘宝nginx的学习使用,安装及反向代理,负载均衡
    Linux5
    Linux4
    Linux权限相关及yum源的配置
    linux基本命令及python3的环境配置
    使用Guava RateLimiter限流
    Runnable与Callable 区别
    [Kafka] 如何保证消息不丢失
    [多线程] 等待所有任务执行完成
    [Docker] 快速安装mysql
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6756059.html
Copyright © 2011-2022 走看看