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,
  • 相关阅读:
    android webView使用
    Android开发者必知的开发资源(转载)
    Android中的消息推送(转载)
    Android消息处理系统——Looper、Handler、Thread(转载)
    Android之单元测试学习(转载)
    ndroid获得Bitmap的三种方法(转载)
    Android性能调优(转载)
    Android的开机流程(转载)
    Android命名规范(自定义)(转载)
    无法解决 equal to 操作中 Latin1_General_CI_AI 和 Chinese_PRC
  • 原文地址:https://www.cnblogs.com/zeakey/p/4558572.html
Copyright © 2011-2022 走看看