zoukankan      html  css  js  c++  java
  • leetcode #1 twoSum问题:简单实用哈希表

    因为不是计算机专业的,算法基础有点差,所以最近开始在leetcode上刷刷题补一补。

    #1 问题链接:twoSum

    问题描述:

    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

    首先拿到题想到的第一个方法就是两层循环去找。迅速写出来提交,提示runtime exceed,也就是时间复杂度超出范围。

    接着我看了下这个题目的tags,有array 和 hash ,那肯定是要用哈希表了。因此用哈希表,一层循环,复杂度O(N)。

    C++代码:

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            vector<int> ret(2,-1);
            unordered_map<int, int> m; 
            for(int i = 0; i < numbers.size(); i ++)
            {
                if(m.find(target-numbers[i]) == m.end())
                    m[numbers[i]] = i;
                else
                {
                    ret[0] = m[target-numbers[i]]+1; 
                    ret[1] = i+1;
                    return ret;
                }
            }
        }
    };

    哈希表就是根据输入的数值去找数值在存储结构中的位置,因此用无序map存储<数值,索引>对。对输入的数字序列进行遍历,当数值 numbers[i]的“另一半”也就是与它相加可得target的那个数不在表中,就将numbers[i]加入表中,如果numbers[i]的“另一半”在表中,那就返回numbers[i]和它的“另一半”的索引。

    另附上python代码:

    class Solution:
        def twoSum(self,nums,target):
            table=dict()
            for i in range(len(nums)):
                if not table.has_key(target-nums[i]):
                    table[nums[i]]=i
                else:
                    return table[target-nums[i]]+1,i+1,
  • 相关阅读:
    JQuery常用函数及功能小结
    JSP +Tomcat数据库访问
    JSP+Tomcat开发环境安装及配置
    去除Win7快捷方式的箭头
    UK Day46 MongoDB Atlas的创建+配置+连接集群
    UK Day46 MongoDB 文档基本操作 增删改查
    UK Day46 MongoDB 集合基本操作
    UK Day46 MongoDB 聚合(aggregate)操作
    MongoDB M001第五章 索引和聚合管道
    公告!
  • 原文地址:https://www.cnblogs.com/zeakey/p/4558572.html
Copyright © 2011-2022 走看看