TwoSum, 在一个列表中,找到两个数的index,使得这两个数加起来等于另一个数。
我用的是一个辅助字典,即空间换时间。字典里存储每个数的互补数(complementary = target - value)
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ map_table = {} for i, val in enumerate(nums): complementary = target - val if map_table.get(complementary) is not None: return [i, map_table.get(complementary)] map_table[val] = i
ThreeSum, 在一个列表中找到所有的三元组,使得三元组中这3个数字加起来等于0。要求是三元组中不能有重复的。
这个就是TwoSum的升级版。对于每个数a,在它后面的数组中,寻找和为a的两个数的组合。
但是直接这样做通过不了OJ,在一些特定的输入下会超时。比如输入为[0, 0, 0,, ...........0, 0],输出应该是[[0, 0, 0]]。
所以可以在原始输入中做些手脚。因为求的是三元组,所以可以删掉原数组中重复项(重复3次以上的数字删掉)。
这应该不是常规解法,但是OJ能过。
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = set() reduced_list = self.remove_duplicate_3(nums) print(reduced_list) for i in range(len(reduced_list)): sum_value = -reduced_list[i] two_values = self.twoSum(reduced_list[i+1:], sum_value) if two_values != []: for values in two_values: values += [reduced_list[i]] result.add(tuple(sorted(values))) return [list(i) for i in result] def twoSum(self, nums, target): map_table = {} result_list = [] for i, val in enumerate(nums): complementary = target - val if map_table.get(complementary) is not None: result_list.append([val, complementary]) map_table[val] = i return result_list def remove_duplicate_3(self, nums): result = {} reduce_list = [] for i in nums: if result.get(i) is None: result[i] = 1 reduce_list.append(i) else: result[i] += 1 if result[i] <= 3: reduce_list.append(i) return reduce_list
数字链表相加,这个简单。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1n = self.recover_decimal(l1) l2n = self.recover_decimal(l2) return self.build_linked_list_decimal(l1n+l2n) def build_linked_list_decimal(self, number): head = None cursor = None while number != 0: node = ListNode(number % 10) if not head: head = node cursor = node else: cursor.next = node cursor = node number = int(number/10) return head or ListNode(0) def recover_decimal(self, l1): number = 0 numbers = [] while l1: numbers.append(l1.val) l1 = l1.next length = len(numbers) for i in range(length): number += numbers[i] * (10**(i)) return number