Created
April 20, 2014 14:55
-
-
Save toliuweijing/11116111 to your computer and use it in GitHub Desktop.
Leetcode[python]: Two Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
# @num list of values. | |
# @return list of tuples in [(val, index)...], i.e. [2,1,3] -> [(1,1),(2,0),(3,2)]. | |
def sortedNumbersWithIndex(self, num): | |
tuples = []; | |
for i in range(len(num)): | |
tup = (num[i], i); | |
tuples.append(tup); | |
tuples.sort(key=lambda tup: tup[0]); | |
return tuples; | |
# @return a tuple, (index1, index2) | |
def twoSum(self, num, target): | |
keyedNum = self.sortedNumbersWithIndex(num); | |
a = 0; | |
b = len(keyedNum)-1; | |
while (a < b): | |
va = keyedNum[a][0]; | |
vb = keyedNum[b][0]; | |
ia = min(keyedNum[a][1], keyedNum[b][1]); | |
ib = max(keyedNum[a][1], keyedNum[b][1]); | |
if (va+vb==target): | |
return (ia+1,ib+1) | |
elif (va+vb<target): | |
a +=1 | |
else: | |
b -=1; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment