码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode刷题记录(python3)

时间:2018-03-08 19:37:26      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:复杂度   har   sub   哈希表   通过   ring   nbsp   next   art   

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移动到重复值的下一位置.

 

LeetCode刷题记录(python3)

标签:复杂度   har   sub   哈希表   通过   ring   nbsp   next   art   

原文地址:https://www.cnblogs.com/limitlessun/p/8530277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!