1.Two Sum
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i, n in enumerate(nums): m = target - n if m in d: return [d[m], i] else: d[n] = i
时间复杂度:O(n),python中的字典其实就是哈希表的应用,所以我们通过字典用哈希表来降低查找的时间复杂度
2.Add Two Numbers
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ node1 = l1 node2 = l2 l3 = ListNode(0) l3.next = ListNode(0)#[0],[0]的特殊情况 node3 = l3 sum1 = 0 coe = 1 while not node1 is None: sum1 += node1.val * coe coe *= 10 node1 = node1.next sum2 = 0 coe =1 while not node2 is None: sum2 += node2.val * coe coe *= 10 node2 = node2.next sum = sum1 + sum2 while sum > 0: node3.next = ListNode(sum % 10) node3 = node3.next sum //= 10 return l3.next
思路非常简单,先将两个单链表中的数字分别提取出来求和,然后将求得的和存入一个单链表.实际上相加这一步也可以直接在原链表中完成,只需要添加判断条件while(l1 or l2 or carry)即可.
3.Longest Substring Without Repeating Characters
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ start = 0 max_length = 0 substring = {} for i, c in enumerate(s): if c in substring and start <= substring[c]:#只有当重复值是在start后面出现时才移动start start = substring[c] + 1#Slding Window的思想 else: max_length = max(max_length, i - start + 1) substring[c] = i return max_length
一开始没有想到用字典,而是直接用str来存储字串,时间复杂度是O(n^2),后来用字典将时间复杂度降到了O(n).注意到仅当字典中出现重复值且该重复值在strat区段里时才移动start.另外用了Sliding Window的思想,每次将strat移动到重复值的下一位置.