码迷,mamicode.com
首页 > 编程语言 > 详细

[Lintcode two-sum]两数之和(python,双指针)

时间:2016-06-18 23:45:42      阅读:770      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://www.lintcode.com/zh-cn/problem/two-sum/

给一个整数数组,找到两个数使得他们的和等于一个给定的数target

备份一份,然后排序。搞两个指针分别从左从右开始扫描,每次判断这两个数相加是不是符合题意,如果小了,那就把左边的指针向右移,同理右指针。然后在备份的数组里找到位置。

 1 class Solution:
 2     """
 3     @param numbers : An array of Integer
 4     @param target : target = numbers[index1] + numbers[index2]
 5     @return : [index1 + 1, index2 + 1] (index1 < index2)
 6     """
 7     def twoSum(self, numbers, target):
 8         # write your code here
 9         tmp = []
10         for i in numbers:
11             tmp.append(i)
12         numbers = sorted(numbers)
13         a = 0
14         b = len(numbers) - 1
15         while True:
16             if numbers[a] + numbers[b] == target:
17                 break
18             elif numbers[a] + numbers[b] < target:
19                 a += 1
20             elif numbers[a] + numbers[b] > target:
21                 b -= 1
22         reta = numbers[a]
23         retb = numbers[b]
24         a = -1
25         b = -1
26         for i in range(0, len(tmp)):
27             if tmp[i] == reta and a == -1:
28                 a = i
29             elif tmp[i] == retb and b == -1:
30                 b = i
31         if a > b:
32             a = a ^ b
33             b = a ^ b
34             a = a ^ b
35         return [a+1, b+1]

 

[Lintcode two-sum]两数之和(python,双指针)

标签:

原文地址:http://www.cnblogs.com/vincentX/p/5597144.html

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