• Leetcode No.1 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

    方法一:

    使用哈希表,时间复杂度O(n),空间复杂度O(n)。遍历数组,对numbers[i],在哈希表中寻找是否有target-numbers[i],如果有则返回结果,没有则将<numbers[i], i+1>添加进哈希表。也就是说当最后找到这一对数字时,是找到了在numbers[i]之前添加进哈希表的对应项,所以返回时的顺序依次是:hash[target-numbers[i]], i+1。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         vector<int> result;
     5         unordered_map<int, int> hash;
     6         for(int i=0;i!=numbers.size();i++){
     7             int findNumber=target-numbers[i];
     8             if(hash.find(findNumber)!=hash.end()){
     9                 result.push_back(hash[findNumber]);
    10                 result.push_back(i+1);
    11                 return result;
    12             }else
    13                 hash[numbers[i]]=i+1;
    14         }
    15     }
    16 };

    方法二:

    先对数组排序,然后使用两个分别指向头尾的指针m, n遍历数组,如果numbers[m]+numbers[n]<target, m++; numbers[m]+numbers[n]>target, n--;否则返回结果。不过因为数组未排序,排序至少要O(nlgn)复杂度,还要另外记下数组元素原来的下标,不如使用哈希表方便。

    作者: mono
    出处: http://www.cnblogs.com/monolock/
    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    之前的博客
    用struts2 s2-045漏洞拿站记录
    修改BlackLowKey皮肤样式,增加占屏比
    SpringBoot自动配置原理
    CAS无锁技术
    CAS单点登录原理解析
    死锁与活锁的区别,死锁与饥饿的区别
    jvm问题
    jdk动态代理的实现原理
    抽象工厂
  • 原文地址:https://www.cnblogs.com/monolock/p/4199954.html
Copyright © 2020-2023  润新知