LeetCode小白菜笔记[1]:Two Sum

来源:互联网 发布:沪牌代拍软件 编辑:程序博客网 时间:2024/06/09 17:47

LeetCode小白菜笔记[1]:Two Sum

1. Two Sum [Easy]

题目:

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 the same element twice.
Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

就是给定一个数组,找到其中的两个值加起来给定特定值,并返回这两个数的indice。

首先,最简单的,考虑暴力的方法

class Solution(object):     def twoSum(self, nums, target):    """    :type nums: List[int]    :type target: int    :rtype: List[int]    """    foundflag = 0    for i in range(len(nums)-1):        for j in range(i+1,len(nums)):        if nums[i] + nums[j] == target :            foundflag = 1            return [i, j]    if foundflag == 0:        print('[*] : No Such Numbers')

结果。。。。

这里写图片描述

Runtime太久了。。。这是个O(n^2)的方法,虽然accepted了但是还是不能算解决了问题。
这告诉我们,暴力不可取。

下面考虑其他方法。由于我们的target给定,对于每一个确定的加数,另一个加数也确定了,因此实际上这是一个在数组中查找元素的问题。并且查找到元素后要返回其下标,所以indice应该时元素作为key对应的value。为了加快查找速度,采用HashTable的方法,以空间换取时间。在python中,dict 数据体即hash table的实现,其存取在数量较少,即没有哈希冲突的时候,都是 O(1) 的。因此先采用hash table把数组元素值作为要进行hash的key,其下标为value。此过程过一遍list,故O(n)。然后在过一遍list,每次都查一下target - nums[i] 在不在dict里,O(n) ,故时间复杂度O(n),但是空间复杂度也是O(n),相比于暴力的O(1)变多啦。

class Solution(object):        def twoSum(self, nums, target):    """    :type nums: List[int]    :type target: int    :rtype: List[int]    """    foundflag = 0    hashtable = dict()    for i in range(len(nums)):        hashtable[nums[i]] = i    for j in range(len(nums)):        if (hashtable.has_key(target-nums[j]) and not hashtable[target-nums[j]] == j):            foundflag = 1            return [hashtable[target-nums[j]], j]    if foundflag == 0:        print ('[*] : No Such Numbers')

这就好多啦,结果如下:

这里写图片描述

然后Solution里面还有更简单的方法,即 One-pass Hash Table,即在过list的过程中,对每一个数,先看hash table中有没有complement,如果有,直接输出,就不用继续计算啦,如果没有,就加到hash table里。这样只用过一边list即可,Complexity时间O(n),空间最多也是O(n)。

class Solution(object):     def twoSum(self, nums, target):    """    :type nums: List[int]    :type target: int    :rtype: List[int]    """    foundflag = 0    hashtable = dict()    for i in range(len(nums)):        if (hashtable.has_key(target - nums[i])):        foundflag = 1        return [hashtable[target - nums[i]], i]        else:        hashtable[nums[i]] = i    if foundflag == 0:        print ('[*] : No Such Numbers')

结果:

这里写图片描述

- 总结
第一次做leetcode,自己还是naive。。。
三种方法:
Brute Force——- Time:O(n^2) ,Space:O(1)
Two-pass Hash——Time:O(n) ,Space:O(n)
One-pass Hash——Time:O(n) ,Space:O(n)

THE END

星期六, 09. 十二月 2017 06:10下午