zoukankan      html  css  js  c++  java
  • [Leetcode] 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

    先排序,再从两头求解,然后找下标,注意可能有相等的元素。找下标的时候可从分别从前后方向找。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         vector<int> v = numbers;
     5         sort(v.begin(), v.end());
     6         int a = 0, b = v.size() - 1;
     7         while (a < b) {
     8             if (v[a] + v[b] > target) {
     9                 b--;
    10             } else if (v[a] + v[b] < target) {
    11                 a++;
    12             } else {
    13                 break;
    14             }
    15         }
    16         for (int i = 0; i < v.size(); ++i) {
    17             if (v[a] == numbers[i]) {
    18                 a = i + 1;
    19                 break;
    20             }
    21         }
    22         for (int i = v.size() - 1; i >= 0; --i) {
    23             if (v[b] == numbers[i]) {
    24                 b = i + 1;
    25                 break;
    26             }
    27         }
    28         vector<int> res;
    29         res.push_back(a > b ? b : a);
    30         res.push_back(a > b ? a : b);
    31         return res;
    32     }
    33 };

     还可以用map、hash_map来做。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         vector<int> res;
     5         map<int, int> mp;
     6         for (int i = 0; i < numbers.size(); ++i) {
     7             if (mp[target-numbers[i]] != 0) {
     8                 int idx1 = mp[target-numbers[i]] > i + 1 ? i + 1 : mp[target-numbers[i]];
     9                 int idx2 = mp[target-numbers[i]] < i + 1 ? i + 1 : mp[target-numbers[i]];
    10                 res.push_back(idx1);
    11                 res.push_back(idx2);
    12                 return res;
    13             }
    14             mp[numbers[i]] = i + 1;
    15         }
    16         return res;
    17     }
    18 };
  • 相关阅读:
    Pollard rho模板
    GDKOI2018游记
    BZOJ2599: [IOI2011]Race
    Codeforces914E. Palindromes in a Tree
    可以删点的并查集
    本月题量 180122晚-180222午
    51nod1238 最小公倍数之和 V3
    51nod1237 最大公约数之和 V3
    hdu5608:function
    51nod1244 莫比乌斯函数之和
  • 原文地址:https://www.cnblogs.com/easonliu/p/3630629.html
Copyright © 2011-2022 走看看