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> result;
     5         unordered_map<int, int> mapping;
     6         for (size_t i = 0; i < numbers.size(); ++i) {
     7             mapping[numbers[i]] = i;
     8         }
     9         for (size_t i = 0; i < numbers.size(); ++i) {
    10             int t = target - numbers[i];
    11             if (mapping.find(t) != mapping.end() && mapping[t] != i) {
    12                 result.push_back(i + 1);
    13                 result.push_back(mapping[t] + 1);
    14                break;
    15             }
    16         }
    17         return result;
    18     }
    19 };
    View Code

    暴力O(n2)超时,由于要求输出的是下标,所以不能排序,利用hash。

    另外题目没有说明的是:要求输出的两个下标是不同的。例如{3, 2, 4} target = 6 应该输出 2,3 而不是1,1.

  • 相关阅读:
    哈希及哈希算法
    十四章课后练习题
    第十章课后题----3
    20151015----知识整理
    第十章练习题----2
    加热水杯
    函数
    异常反馈
    20151013知识体系整理,需与20151011相整合
    Java随机输出验证码包含数字、字母、汉字
  • 原文地址:https://www.cnblogs.com/dengeven/p/3604818.html
Copyright © 2011-2022 走看看