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 };
  • 相关阅读:
    使用vs2010编译 Python SIP PyQt4
    谷歌编程指南
    【转】微策略面经相关资料
    KMP 算法
    C++ 拷贝构造函数
    虚继承 虚表 定义一个不能被继承的类
    cache的工作原理
    背包问题
    【转】C/C++ 内存对齐
    【转】 Linux/Unix 进程间通信的各种方式及其比较
  • 原文地址:https://www.cnblogs.com/easonliu/p/3630629.html
Copyright © 2011-2022 走看看