码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:1-Two Sum

时间:2017-12-12 20:47:11      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:等于   nbsp   设置   复杂度   i+1   个数   because   for   each   

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

题意:找出数组num中的两个数,它们的和为一个给定的数target,要求返回这两个数的索引,已知只有一组解。

方法1:

复制数组num,对num的副本进行排序,然后设置头尾指针遍历num的副本找到符合要求的两个数,再从原数组num中得到这两个数的索引(找索引时一个从头找,一个从尾找,防止找到同一个数)

 

 1 ‘‘‘
 2 日期:2017-12-12
 3 实现思路:先排序,再设置头尾指针,从两头遍历,直到相加等于target
 4 ‘‘‘
 5 class Solution:
 6     def twoSum(self, num, target):
 7         numtosort=num[:]  #复制num数组
 8         numtosort.sort()  #对复制的数组进行排序
 9         i=0               #头指针
10         j=len(numtosort) - 1  #尾指针
11         index = []        #存放索引
12         while i<j:
13             if numtosort[i]+numtosort[j]==target:   #找到满足条件的元素
14                 for k in range(len(num)):           #在原数组中找第一个元素的位置(从左往右遍历)
15                     if num[k]==numtosort[i]:
16                         index.append(k)
17                         break
18                 for k in range((len(num)-1),-1,-1):  #在原数组中找第二个元素的位置(从右往左遍历)
19                     if num[k]==numtosort[j]:
20                         index.append(k)
21                         break
22                 index.sort()                        #将存放索引的list进行排序
23                 break
24             elif numtosort[i]+numtosort[j]<target:   #移动头指针
25                 i=i+1
26             elif numtosort[i]+numtosort[j]>target:  #移动尾指针
27                 j=j-1
28         return (index[0],index[1])
29 
30 if __name__==__main__:
31     num=[2,7,11,15]
32     target=9
33     solution=Solution()
34     print(solution.twoSum(num,target))

 方法2:hash

 1 ‘‘‘
 2 日期:2017-12-12
 3 实现思路:hash。
 4 时间复杂度:O(n)
 5 ‘‘‘
 6 class Solution:
 7     def twoSum(self,num,target):
 8         d = {}  #创建一个空dict
 9         for i in range(len(num)):    #遍历num数组
10             x = num[i]               #数组num的当前值
11             if target-x in d:        #若另一个数已经存在于dict中,则两个数都已找到,输出即可
12                 return (d[target-x],i)
13             d[x] = i                 #若另一个加数还没在dict中,则将当前数存入dict中,其中数是key,索引是value
14 if __name__==__main__:
15     num=[7,11,15,2]
16     target=9
17     solution=Solution()
18     print(solution.twoSum(num,target))

 

 

Leetcode:1-Two Sum

标签:等于   nbsp   设置   复杂度   i+1   个数   because   for   each   

原文地址:http://www.cnblogs.com/zj83839/p/8028614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!