GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Leetcode_python/Solutions/015_3Sum.py at master · xtymichael/Leetcode_python Expand file tree/ Copy path015_3Sum.pyMore file actions 64 lines (52 loc) · 1.67 KB / Copy path015_3Sum.pyFile metadata and controls64 lines (52 loc) · 1.67 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 class Solution: # @param {integer[]} nums # @return {integer[][]} def threeSum(self, nums): d = dict() result = [] for i in nums: if i not in d: d[i] = 1 else: d[i] += 1 sortD = d.keys() for j in range(len(sortD)): first = sortD[j] d[first] -= 1 for k in range(j, len(sortD)): second = sortD[k] if d[second] > 0: d[second] -= 1 else: continue third = - (first + second) temp = sorted([first, second, third]) if third in sortD and d[third] > 0 and temp not in result: result.append(temp) d[second] += 1 d[first] += 1 return result ########################################################################### class Solution: # @param {integer[]} nums # @return {integer[][]} def threeSum(self, nums): if len(nums) <3: # deal with special input return [] elif len(nums) == 3: if sum(nums) == 0: return [sorted(nums)] nums = sorted(nums) # sorted, O(nlgn) ans = [] for i in range(len(nums) -2): j = i+1 k = len(nums) -1 # hence i < j < k while j<k: # if not cross line temp_sum = nums[i] + nums[j] + nums[k] if temp_sum == 0: ans.append((nums[i], nums[j], nums[k])) if temp_sum > 0: # which means we need smaller sum, move k backward, remember we sort the array k -= 1 else: j += 1 return list(set(tuple(ans))) # I bet this is not the best way to eliminate duplicate solutions |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |