N Sum
題目: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???????????????
轉載于:https://www.cnblogs.com/ylHe/p/6066538.html
總結
- 上一篇: 第四十四章 微服务CICD(6)- gi
- 下一篇: 虚拟主机的配置