zoukankan      html  css  js  c++  java
  • LeetCode 1.Two Sum

    Two Sum

    Given an array of integers, 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.

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

    Solution

     1 #include<vector>
     2 using namespace std;
     3 class Solution {
     4 public:
     5    vector<int> twoSum(vector<int> &numbers, int target) {
     6         vector<int> copyNumbers=numbers;
     7         sort(copyNumbers.begin(), copyNumbers.end());
     8         
     9         vector<int> result;
    10         int minIndex=0;
    11         int maxIndex=numbers.size()-1;
    12         int sum;
    13         while(minIndex<=maxIndex)
    14         {
    15             sum=copyNumbers[minIndex]+copyNumbers[maxIndex];
    16             if(sum==target)
    17             {
    18                 vector<int>::iterator minIte=find(numbers.begin(),
                       numbers.end(),copyNumbers[minIndex]);
    19 vector<int>::reverse_iterator maxIte=find(numbers.rbegin(),
                            numbers.rend(),copyNumbers[maxIndex]);
    20 21 result.push_back(&*minIte-&numbers[0]+1); 22 result.push_back(&*maxIte-&numbers[0]+1); 23 break; 24 } 25 else if(sum>target) 26 { 27 maxIndex--; 28 } 29 else 30 minIndex++; 31 } 32 sort(result.begin(),result.end()); 33 return result; 34 } 35 };
  • 相关阅读:
    ffmpeg-3.2.4-static-win32-for-XP-bin.tar.xz
    FFmpeg Scaler Options
    MinGW GCC 6.3.0 2017年3月份出炉啦
    ffmpeg-201701[10,16,21,23,25]-bin.7z
    ffmpeg-201612[01,08,10,17,21,27,30]-bin.7z
    Firefox Portable Developer 52.0.0.6176-6178
    DIR 按文件名中数字大小进行排序
    ffmpeg-20161104[07,10,16,21,22,27,30]-bin.7z
    gnuWin32-mini-2016.10.30
    gnu coreutils-8.25 for win32 static
  • 原文地址:https://www.cnblogs.com/kyokuhuang/p/4190248.html
Copyright © 2011-2022 走看看