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 }
  • 相关阅读:
    php......房屋租赁练习
    php......调研投票练习
    数据访问......单条件查询与多条件查询
    数据访问......简单练习
    数据访问......增删改查
    数据访问
    面向对象练习
    php正则表达式和数组
    php面向对象加载类
    php类和对象(二)
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6756059.html
Copyright © 2011-2022 走看看