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 };
  • 相关阅读:
    寒假第七天
    寒假第六天
    寒假第五天
    寒假第四天
    leetcode 105 从前序与中序遍历序列构造二叉树
    leetcode 268 丢失的数字
    leetcode 141 环形链表
    判断顶点是否在三角形内部
    java 基本数据类型
    leetcode 20 有效的括号
  • 原文地址:https://www.cnblogs.com/kyokuhuang/p/4190248.html
Copyright © 2011-2022 走看看