Created
January 11, 2019 23:11
-
-
Save twsiyuan/e0a280495b0ded57b9d745cbd4328476 to your computer and use it in GitHub Desktop.
python code for https://leetcode.com/problems/3sum/submissions/
This file contains hidden or 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: | |
def threeSum(self, nums): | |
""" | |
:type nums: List[int] | |
:rtype: List[List[int]] | |
""" | |
nums.sort() | |
m = {} | |
for i, num in enumerate(nums): | |
if not num in m: | |
m[num] = [i] | |
else: | |
m[num].append(i) | |
rs = {} | |
for i, a in enumerate(nums): | |
for k, b in enumerate(nums[i+1:]): | |
k = k+i+1 #fix index | |
s = a + b | |
if -s in m: | |
if m[-s][-1] > k: | |
r = [a, b, -s] | |
key = hash(r) | |
rs[key] = r | |
return [rs[x] for x in rs] | |
def hash(obj): | |
r = "" | |
for k, v in enumerate(obj): | |
r = r + str(k) + str(v) | |
return r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment