Leetcode# 1. Two Sum(哈希)

来源:互联网 发布:电脑程序员培训班 编辑:程序博客网 时间:2024/06/05 17:38

玩了两天了,又要开始学习啦,打算从leetcode第一道题目开始刷,一周至少三道,其余时间学习项目。保持手感。
不为刷题而刷题,策略是从题号为1的开始按照顺序刷,对于一道题尝试使用c++和python两种语言多种方法解决问题。开始ing!!!!!!

Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题意:给你一个整数数组,返回两个数的索引,使它们相加到一个特定的目标,你可以假设每一个输入都只有一个解决方案,而且你不能使用相同的元素两次。

解决方案一:C++版

解题思路:简单题目,两个for循环,注意leecode的提交代码的不同,只需要提交方法就可以,而且方法里面多使用vector动态数组)
时间复杂度:O(n*n)

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> res;        for(int i=0; i<nums.size(); i++)        {            for (int j=i+1; j<nums.size(); j++)            {                if(nums[i]+nums[j]==target)                {                    res.push_back(i);                    res.push_back(j);                }              }        }        return res;    }};

网上好多人说这种暴力的方法时间超限,然而我却过了,不过显然这种解法,不是我们想要的。
这里写图片描述

解决方案二:c++优化版(哈希)

解题思路:首先我们知道哈希表查找的时间复杂度是O(1),这里可以借助哈希表查找可以将时间复杂度降低到O(n),下面就是构造哈希函数,我们知道map里面有一个方法find()查找之后返回的key值,end()方法则是是否查找到最后,利用这两种方法构造哈希函数
hash[i]表示nums中数值为i的下标
时间复杂度为O(n)比前面的暴力解法优化了。

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> res;        map<int, int>hash; //hash[i]表示nums中数值为i的下标        for(int i=0; i<nums.size(); i++)        {             if(hash.find(target - nums[i])!= hash.end())           {               res.push_back(hash[target-nums[i]]);               res.push_back(i);               return res;           }           hash[nums[i]]=i;        }    }};

解决方案三:python版

解题思路:使用列表的index方法,可以直接返回数值的下标,每次从列表中取出一个数的下标indice,判断target-nums[indice]是否在数据中且和下标和indice不同,找到了就返回。
时间复杂度0(n)

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        res = []        nums_len = len(nums)        for indice in range(0,nums_len):            temp = target - nums[indice]            if temp in nums and indice != nums.index(temp):                res.append(indice)                res.append(nums.index(temp))                return res                              

综合上面三种方法,第二种和第三种思路相同都是构造哈希函数,个人比较喜欢第三种,直接利用列表的index()返回下标的方法,不过第二种也是很常用的,看这个的爱好,本人最近正在学习python所以解题以后都会尝试着c++和python两种。
github链接:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23%201.%20Two%20Sum%EF%BC%88%E5%93%88%E5%B8%8C%EF%BC%89.md

原创粉丝点击