LeetCode专题-Python实现之第1题:Two Sum

导航页-LeetCode专题-Python实现

相关代码已经上传到github:https://github.com/exploitht/leetcode-python
文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

1、读题

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].

有一个整型数组,返回满足特定条件的2个数字的索引,这2个数字相加的值等于特定的目标数字。假设每一次输入都会有唯一的输出而且同一个元素不会使用2次。

2、初步解题

很简单的一个思路就是循环遍历数组,做一个if判断,满足条件返回索引。编码很简单,如下:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # i从列表的第一个到倒数第二个,也就是nums[0, Len-2]
        # j从i的后面一个开始到nums[Len-1]
        # 下面的len(nums)-1而不是-2是因为range(1,2)返回的是[1]不含2
        for i in range(0, len(nums) - 1):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

3、第一次优化

上面的解决方案for套for明显时间复杂度是O(n2),这里的2是平方,空间复杂度是O(n),思考一下有没有优化的办法的?
循环有嵌套,能不能不要循环套循环?
这里的循环嵌套是为了对每一个元素判断一次序列中是否有匹配元素,有的话返回双方索引,所以可以考虑在寻找匹配的元素这一步,不要一直去遍历,如果元素值和索引生成一个哈希表,那么匹配的过程只要查询哈希表就行了,这个过程的复杂度是O(1),下面尝试给出一种解决方案:

class Solution(object):
    def twoSum(self, nums, target):
        num_dict = dict()
        # 第一次循环建立值和索引的哈希表
        for index, value in enumerate(nums):
            num_dict[value] = index
        # 第二次循环判断目标target-nums里的元素得到的结果是不是在前面得到的字典中,如果存在则返回双方索引
        for index, value in enumerate(nums):
            if (target - value) in num_dict and num_dict[target - value] != index:
                return [index, num_dict[target - value]]

4、第二次优化

上面一个方案通过2次循环(非嵌套)的方式,遍历了2次nums列表得到了需要的结果,时间复杂度变成了O(n)。
美中不足的是循环还是进行了2次,这里是先生成一个哈希表,然后循环过程中判断当前元素和哈希表中的数据相加是否满足条件,第一次循环的过程中能不能做一个判断呢?
所以下一个思路是遍历nums,遍历过程中判断当前元素和哈希表中的值相加能不能满足要求,也就是target-当前元素的值在哈希表中是否存在,如果存在,就返回2个索引,如果不存在,那么当前元素存入哈希表。实现如下:

class Solution(object):
    def twoSum(self, nums, target):
        num_dict = dict()
        for index, value in enumerate(nums):
            want = target - value
            if want in num_dict:
                return [num_dict[want], index]
            num_dict[value] = index

声明:文章中涉及的代码全部本地手写然后上传到leetcode验证通过,优化部分思路参考官网内容

posted @ 2017-09-22 21:59  胡说云原生  阅读(333)  评论(0编辑  收藏  举报