• 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 }
  • 相关阅读:
    完全数
    100c之29:求具有abcd= ( ab + cd )^2 性质的四位数
    完全数
    100c之22:计算车速
    100c之21:4位反序数
    100c之28:回文数
    AJAX
    网站运营十条定律 刚刚好
    QQ也流氓了 刚刚好
    服务器变肉鸡了 刚刚好
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6756059.html
Copyright © 2020-2023  润新知