zoukankan      html  css  js  c++  java
  • LeetCode Problem 2: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:暴力搜索,两层循环。时间:O(n^2),空间:O(1),可能出现超时

    思路2:考虑使用map或者hash_map,遍历输入的numbers,在map映射表中寻找target-numbers[i],C++ STL中map使用红黑树实现,查找元素时间O(logn),总时间O(nlogn)

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         
     5         vector<int> result;
     6         map<int, int> hashMap;
     7         
     8         for(int i = 0; i < numbers.size(); i++) {
     9             
    10             if(!hashMap.count(numbers[i])) 
    11                 hashMap.insert(pair<int,int>(numbers[i], i));   // <value, key>
    12                 
    13             if(hashMap.count(target - numbers[i]))  {
    14                 int n = hashMap[target - numbers[i]];   //get the second number's position
    15                 if(n < i)   {
    16                     result.push_back(n + 1);
    17                     result.push_back(i + 1);
    18                     return result;
    19                 }
    20                 
    21                 //unnecessary
    22                 /*if(n > i)    {
    23                     result.push_back(i + 1);
    24                     result.push_back(n + 1);
    25                     return result;
    26                 }*/
    27             }
    28         }
    29     }
    30 };

    附LeetCode建议解决方案

  • 相关阅读:
    吴裕雄--天生自然 Zookeeper学习笔记--Zookeeper 权限控制 ACL
    【机器学习】机器学习基础
    【QT】利用pyqt5实现简单界面
    【Mathtype】安装Mathtype后,word无法粘贴的问题
    【优化方法】牛顿法
    博客样式设置
    2018.8.28 练习赛
    2018.8.27 练习赛
    2018.8.26 练习赛
    2018.8.25 练习赛
  • 原文地址:https://www.cnblogs.com/fanyabo/p/4183158.html
Copyright © 2011-2022 走看看