Skip to content

Instantly share code, notes, and snippets.

@toliuweijing
Created April 20, 2014 14:55
Show Gist options
  • Save toliuweijing/11116111 to your computer and use it in GitHub Desktop.
Save toliuweijing/11116111 to your computer and use it in GitHub Desktop.
Leetcode[python]: Two Sum
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