菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
86
0

N Sum

原创
05/13 14:22
阅读数 15003


题目:N 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.

样例: 
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, 
return [0, 1].

解决思路:像这种有关联关系的输入输出,C解决的话要考虑用哈希,Python的话我们直接考虑用字典解决就可以了,遍历数组,并且保存在字典中,查找字典中是否有符合的数字若符合直接返回数组下标和字典的value。 
代码: 
class Solution(object):  #这里我用Python解决
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in xrange(len(nums)):
            x = nums[i]
            if target - x in dict:
                return (dict[target - x],i)
            dict[x] = i

知识点:

range和xrange的区别

>>> a = range(5)
>>> print type (a)
<type 'list'> #我们可以看出range生成的是一个list对象

>>> print range(5)[0] #从list列表中打印list[0]
0
>>> b = xrange(5)
>>> print type(b)
<type 'xrange'>

>>> print xrange(5)[0]#而xrange是一个xrange类型,不会直接生成一个list,而是在每次调用的时候返回其中的一个值,节省内存
0               

发表评论

0/200
86 点赞
0 评论
收藏