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 };
  • 相关阅读:
    文件字符输入输出流
    ava.io.InputStream & java.io.FileInputStream
    java.io.OutputStream & java.io.FileOutputStream
    java.lang.String & java.lang.StringBuilder
    文件过滤器
    递归
    原生camera应用 保存设置界面参数方法
    android 获取调用camera service的进程
    linux 查找,替换 常用命令
    将一个项目修改记录提交另外一个项目-> patch获取提交记录,repo 提交代码
  • 原文地址:https://www.cnblogs.com/easonliu/p/3630629.html
Copyright © 2011-2022 走看看