leetcode | 1. Two sum 解题报告

来源:互联网 发布:linux中etc是什么意思 编辑:程序博客网 时间:2024/05/22 17:25

一、题目

题目链接:https://leetcode.com/problems/two-sum/#/description

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

二、思路

1. 最初的想法是使用两层遍历,外层循环i从0 - n-1,内层循环j从i - n-1,当符合条件时返回[i, j]。该算法时间复杂度为O(n^2),空间复杂度为O(1)。Python代码如下:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        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]

return False

2. 后来参考了leetcode中的时间复杂度最优答案(为O(n)),使用了python中的字典,将两层嵌套变为线性查找。使用字典dict,对于每个nums中的元素nums[i],查看target - nums[i]是否在字典dict中,如果在,则直接返回[i, dict[target - nums[i]],如果不在,则把 target - nums[i] : i 存入dict。

这样的if-else结构可以把本来需要先存入字典再查找的两遍遍历整合为一遍。

另外target - nums[i]作为key的好处是便于查找,而且即使出现了两个元素值相同的情况,可以把dict中的i替换掉。

代码如下:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
       :rtype: List[int]
    """
       

dict = {}
        for i in range(0, len(nums)):
            if nums[i] in dict.keys():
                return [i, dict[nums[i]]]
           
else:

dict[target - nums[i]] = i 
        return False

 三、Python的dict

1. 操作

  参考:http://blog.csdn.net/wangran51/article/details/8440848

OperationResultNoteslen(a)the number of items in a 得到字典中元素的个数
 a[k]the item of a with key k 取得键K所对应的值
(1), (10)a[k] = vset a[k] to v 设定键k所对应的值成为v
 del a[k]remove a[k] from a 从字典中删除键为k的元素
(1)a.clear()remove all items from a 清空整个字典
 a.copy()a (shallow) copy of a 得到字典副本
 k in aTrue if a has a key k, else False 字典中存在键k则为返回True,没有则返回False
(2)k not in aEquivalent to not k in a   字典中不存在键k则为返回true,反之返回False(2)a.has_key(k)Equivalent to k in a, use that form in new code 等价于k in a a.items()a copy of a's list of (keyvalue) pairs 得到一个键,值的list(3)a.keys()a copy of a's list of keys 得到键的list(3)a.update([b])updates (and overwrites) key/value pairs from b从b字典中更新a字典,如果键相同则更新,a中不存在则追加(9)a.fromkeys(seq[value])Creates a new dictionary with keys from seq and values set to value 
(7)a.values()a copy of a's list of values(3)a.get(k[x])a[k] if k in a, else x(4)a.setdefault(k[x])a[k] if k in a, else x (also setting it)(5)a.pop(k[x])a[k] if k in a, else x (and remove k)(8)a.popitem()remove and return an arbitrary (keyvalue) pair(6)a.iteritems()return an iterator over (keyvalue) pairs(2), (3)a.iterkeys()return an iterator over the mapping's keys(2), (3)a.itervalues()return an iterator over the mapping's values(2), (3)


2. dict原理

参考:https://foofish.net/python_dict_implements.html

字典类型是Python中最常用的数据类型之一,它是一个键值对的集合,字典通过键来索引,关联到相对的值,理论上它的查询复杂度是 O(1)。

哈希表 (HASH TABLES)

哈希表(也叫散列表),根据关键值对(Key-value)而直接进行访问的数据结构。它通过把key和value映射到表中一个位置来访问记录,这种查询速度非常快,更新也快。而这个映射函数叫做哈希函数,存放值的数组叫做哈希表。 哈希函数的实现方式决定了哈希表的搜索效率。具体操作过程是:

数据添加:把key通过哈希函数转换成一个整型数字,然后就将该数字对数组长度进行取余,取余结果就当作数组的下标,将value存储在以该数字为下标的数组空间里。

数据查询:再次使用哈希函数将key转换为对应的数组下标,并定位到数组的位置获取value。

但是,对key进行hash的时候,不同的key可能hash出来的结果是一样的,尤其是数据量增多的时候,这个问题叫做哈希冲突。如果解决这种冲突情况呢?通常的做法有两种,一种是链接法,另一种是开放寻址法,Python选择后者。

0 0