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 };
  • 相关阅读:
    Gym 100553B Burrito King 无脑背包
    BestCoder Round #85 A B C
    poj 1687 Buggy Sat 简单计算几何
    HDU 1863 Kruskal求最小生成树
    记2016商大ACM省赛
    COMP9517 Week7 Tracking
    COMP9517 week7 Motion
    COMP9313 week7b Spark SQL
    COMP9313 Week 7 Product Quantization and K-Means Clustering
    COMP9517 lab3 image segementation
  • 原文地址:https://www.cnblogs.com/kyokuhuang/p/4190248.html
Copyright © 2011-2022 走看看