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 }
  • 相关阅读:
    Jsp的内置标签和jstl标签
    Jsp中的EL表达式
    JSP和servlet结合案例
    Jsp:内置对象和四种域对象的理解
    编码实战Web端联系人的增删改查
    Session案例
    Cookie案例分析
    会话数据的保存——cookie
    ServletContext和ServletConfig
    Servlet(1)
  • 原文地址:https://www.cnblogs.com/wujufengyun/p/6756059.html
Copyright © 2011-2022 走看看