LeetCode Algorithms number1: two Sum

YeShukai 2016-09-29 02:35:13
Number1: two Sum

Question:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析:
本题的意思是:给出一个数组和一个target值,当数组里面的两个数相加等于target值时,以List(或数组)形式返回该两个数的下标。例如数组 nums = [0,4,3,0],target=0, 要返回的结果为:[0,3]

思路:
在Python中,貌似并没有数组的概念,但List和数组很相似,以下就用List来表示数组。具体思路大致如下:
1. 将List以(index,value)形式保存到新的List中。由于最后结果要返回的是List中元素的下标,因此需要记录List最初的index和value,以tuple形式保存,形如:[(index,value),(index,value),(index,value),...,(index,value)]。在保存时,需要用到enumerate函数,该函数是Python的内置函数,用来遍历List中的index和value。
num = []
for (index,value) in enumerate(nums):
num.append((index,value))

以上述nums = [0,4,3,0]为例,利用enumerate函数保存index和value的结果为:num = [(0,0),(1,4),(2,3),(4,0)]
2. 将新的List按照value值从小到大进行排序。用到了python内置的sorted函数和lambda函数。
numsSort =  sorted(num,key=lambda x:x[1])

排序后的结果为:numsSort = [(0,0),(3,0),(2,3),(1,4)]
3. 定义两个变量充当指针,分别指向首尾两个tuple。命名为left和right,并求出首尾的value和,赋值给sum。
left = 0
right = len(numsSort)-1
sum = numsSort[left][1] + numsSort[right][1]

4. 设置循环来比较sum值和target值的大小。如果sum<target, left++;如果sum>target, right--;直到sum = target为止。
然后返回left和right位置上的元组的index。
以numsSort = [(0,0),(3,0),(2,3),(1,4)]为例,如果target=0,则最后的left=0,right=1,即left表示List中的第0个tuple,right表示List中的第1个tuple。此时,第0个tuple中的index为0,第1个tuple中的index为3,所以最后的返回结果就是[0,3],即原始List中目标元素的下标。

具体程序如下:
[code=python]class Solution(object):
def twoSum(self, nums, target):
#Use enumerate funtion to record the list which named nums
#index and value as a tuple
num = []
for (index,value) in enumerate(nums):
num.append((index,value))

numsSort = sorted(num,key=lambda x:x[1])

#index and sum the first and last number of the list
left = 0
right = len(numsSort)-1
sum = numsSort[left][1] + numsSort[right][1]
#Compare the value of sum and target
while(left < right):
if sum < target:
left += 1
sum = numsSort[left][1] + numsSort[right][1]
elif sum > target:
right -= 1
sum = numsSort[left][1] + numsSort[right][1]
elif sum == target:
return [numsSort[left][0],numsSort[right][0]]


以上是本人对该题的看法和总结,由于自己菜鸟一个,所以欢迎大家来批评和指正,希望能和大家一起进步。


...全文
255 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧