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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode two-sum]两数之和(python,双指针)相关的知识,希望对你有一定的参考价值。

题目链接: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,双指针)的主要内容,如果未能解决你的问题,请参考以下文章

56 两数之和

[LintCode] Two Sum 两数之和

LintCode 56. 两数之和

两数之和

1. 两数之和

leetcode_两数之和