高频算法题

3. 无重复字符的最长子串

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        setc = set()
        n = len(s)
        rk = -1
        ans = 0

        for i in range(n):
            if i != 0:
                setc.remove(s[i-1])
            while rk + 1 < n and s[rk + 1] not in setc:
                setc.add(s[rk+1])
                rk += 1

            ans = max(ans,rk-i+1)
        return ans 
            

215. 数组中的第K个最大元素

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        def partition(nums,l,r):
            privot = nums[r]
            i = l-1
            for j in range(l,r):
                if nums[j]  >= privot:
                    i += 1
                    nums[i],nums[j] = nums[j],nums[i]
            nums[i+1],nums[r] = nums[r],nums[i+1]
            return i+1
            


        l = 0
        r = len(nums) -1
        while True:
            privot_index = partition(nums,l,r)
            if privot_index == k-1:return nums[k-1]
            elif privot_index < k-1:
                l = privot_index + 1
            else:
                r = privot_index -1

912. 排序数组

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        def quick_sort(start,end):
            if start >= end : return 

            idx = random.randint(start,end)
            nums[start],nums[idx] = nums[idx],nums[start]
            privor = nums[start]
            l,r = start,end 
            while l < r:
                while l < r and nums[r] >= privor:
                    r -= 1

                while l < r and nums[l] <= privor:
                    l += 1 
                
                nums[l],nums[r] = nums[r],nums[l]

            nums[start],nums[l] = nums[l],nums[start]
            quick_sort(start,l-1)
            quick_sort(l+1,end)

        quick_sort(0,len(nums)-1)
        return nums

1. 两数之和

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        t_dict = {}
        for i,num in enumerate(nums):
            if num in t_dict:
                return [t_dict[num],i]
            t_dict[target-num] = i
        return []

53. 最大子序和

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # dp = [0] * len(nums)
        # dp[0] = nums[0]
        # for i in range(1,len(nums)):
        #     if dp[i-1] > 0:
        #         dp[i] = dp[i-1] + nums[i]
        #     else:
        #         dp[i] = nums[i]
        # return max(dp)
        sum_v = nums[0]
        max_v = nums[0]
        for i in range(1,len(nums)):
            if sum_v > 0:
                sum_v += nums[i]
            else:
                sum_v = nums[i]
            max_v = max(max_v,sum_v)
        return max_v 
        

160. 相交链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        A,B = headA,headB 
        while A != B:
            A = A.next if A else headB 
            B = B.next if B else headA 
        return A 

21. 合并两个有序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        cur = dum = ListNode(0)
        
        while l1 and l2 :
            if l1.val < l2.val:
                cur.next,l1 = l1,l1.next  
            else:
                cur.next,l2 = l2,l2.next 
            cur = cur.next 
        cur.next = l1 if l1 else l2 
        return dum.next

15. 三数之和

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        res = []
        if n < 3:
            return []
        nums.sort()

        for i in range(n):
            if nums[i] > 0: return res 
            if i > 0 and nums[i] == nums[i-1]:continue
            L = i+1
            R = n - 1

            while L < R:
                if nums[i] + nums[L] + nums[R] == 0:
                    res.append([nums[i],nums[L],nums[R]])
                    while L < R and nums[L] == nums[L+1]:
                        L += 1
                    while L < R and nums[R] == nums[R - 1]:
                        R -= 1
                    
                    L += 1
                    R -= 1
                elif nums[i] + nums[L] + nums[R] > 0:
                    R -= 1
                else:
                    L += 1
        return res

141. 环形链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        if not head or not head.next : return False 
        slow,fast = head,head.next  
        while slow != fast:
            if not fast or not fast.next:
                return False
            slow = slow.next 
            fast = fast.next.next 
            
        return True

102. 二叉树的层序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        if not root:
            return res 
        
        queue = [root]
        while queue:
            n = len(queue)
            tmp = []
            for _ in range(n):
                r = queue.pop(0)
                tmp.append(r.val)
                if r.left:
                    queue.append(r.left)
                if r.right:
                    queue.append(r.right)
            res.append(tmp)

        return res 

415. 字符串相加

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        res = ""
        i,j,carry = len(num1) - 1,len(num2) - 1,0

        while i >= 0 or j >= 0:
            n1 = int(num1[i]) if i >= 0 else 0
            n2 = int(num2[j]) if j >= 0 else 0 

            tmp = n1 + n2 + carry 
            carry = tmp // 10 
            res = str(tmp % 10) + res 

            i,j = i - 1, j - 1

        res = "1" + res  if carry else res 
        return res 

103. 二叉树的锯齿形层序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        res = []
        if not root:
            return res 
        queue = [root]
        isLeft = True
        while queue:
            n = len(queue)
            tmp = []
            for i in range(n):
                
                r = queue.pop(0)
                
                tmp.append(r.val)
                if r.left:
                    queue.append(r.left)
                if r.right:
                    queue.append(r.right)
            if isLeft:
                res.append(tmp)
            else:
                res.append(tmp[::-1])
            isLeft = False if isLeft else True 
        return res

236. 二叉树的最近公共祖先

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or root == p or root == q:return root 
        left = self.lowestCommonAncestor(root.left,p,q)
        right = self.lowestCommonAncestor(root.right,p,q)
        if not left : return right 
        if not right: return left 
        return root 

20. 有效的括号

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'(':')','{':'}','[':']','?':'?'}
        stack = ['?']

        for c in s:
            if c in dic:
                stack.append(c)
            elif dic[stack.pop()] != c:
                return False
        return len(stack) == 1

142. 环形链表 II

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow,fast = head,head 
        while True:
            if not (fast and fast.next):return 
            fast = fast.next.next 
            slow = slow.next 
            if fast == slow:
                break
        fast = head 
        while fast != slow:
            fast,slow = fast.next,slow.next 
        return fast

704. 二分查找

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        l,r = 0,len(nums)-1 
        while l <= r: 
            mid = l+(r-l) // 2
            if nums[mid] == target:
                return mid 
            elif nums[mid] < target:
                l = mid + 1
            else:
                r = mid - 1
        return -1
        

94. 二叉树的中序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        # res = []
        # def dfs(root):
        #     if not root:
        #         return 
        #     dfs(root.left)
        #     res.append(root.val)
        #     dfs(root.right)
        
        # dfs(root)
        # return res 
        stack,rst = [root],[]
        while stack:
            i = stack.pop()
            if isinstance(i,TreeNode):
                stack.extend([i.right,i.val,i.left])
            elif isinstance(i,int):
                rst.append(i)
        return rst

5. 最长回文子串

class Solution:
    def aroundCenter(self,s,left,right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return left + 1 , right - 1

    def longestPalindrome(self, s: str) -> str:
        start,end = 0,0

        for i in range(len(s)):
            left1,right1 = self.aroundCenter(s,i,i)
            left2,right2 = self.aroundCenter(s,i,i+1)

            if right1 - left1 > end - start:
                start,end = left1,right1 
            
            if right2 - left2 > end - start:
                start,end = left2,right2 
        
        return s[start:end+1]

206. 反转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        preNode = None 
        curNode = head
        while curNode:
            tmp = curNode.next 
            curNode.next = preNode
            preNode = curNode
            curNode = tmp 
        return preNode

300. 最长递增子序列

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        if not nums: return 0 
        dp = [1] * len(nums)
        
        for i in range (len(nums)):
            for j in range(i):
                if nums[j] < nums[i]:
                    dp[i] = max(dp[i],dp[j] + 1)
        return max(dp)

670. 最大交换

class Solution:
    def maximumSwap(self, num: int) -> int:
        nums = [n for n in str(num)]
        
        index_arr = [len(nums)] * len(nums)
        max_index = len(nums) - 1

        for i in range(len(nums)-1,-1,-1):
            if nums[i] > nums[max_index]:max_index = i 
            index_arr[i] = max_index
        
        for i in range(len(nums)):
            if nums[i] != nums[index_arr[i]]:
                nums[i],nums[index_arr[i]] = nums[index_arr[i]],nums[i]
                break 

        return int("".join(str(n) for n in nums))

19. 删除链表的倒数第 N 个结点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        pre = ListNode(0)
        pre.next = head
        slow,fast = pre,pre
        t = 0
        while fast.next:
            if t >= n:slow = slow.next 
            fast = fast.next
            t += 1
        slow.next = slow.next.next
        return pre.next 

5. 最长回文子串

class Solution:
    def aroundCenter(self,s,left,right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return left + 1 , right - 1

    def longestPalindrome(self, s: str) -> str:
        start,end = 0,0

        for i in range(len(s)):
            left1,right1 = self.aroundCenter(s,i,i)
            left2,right2 = self.aroundCenter(s,i,i+1)

            if right1 - left1 > end - start:
                start,end = left1,right1 
            
            if right2 - left2 > end - start:
                start,end = left2,right2 
        
        return s[start:end+1]

69. x 的平方根

class Solution:
    def mySqrt(self, x: int) -> int:
        left = 0
        right = x 
        ans = -1

        while left <= right:
            mid = left + (right - left) // 2
            if mid ** 2 <= x:
                ans = mid 
                left = mid + 1
            else:
                right = mid - 1
        return ans 

148. 排序链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        if not head or not head.next : return head 
        slow,fast = head,head.next 

        while fast and fast.next :
            slow = slow.next 
            fast = fast.next.next 
        mid,slow.next = slow.next,None 

        left,right = self.sortList(head),self.sortList(mid)

        h = res = ListNode(0)

        while left and right:
            if left.val < right.val: h.next,left = left,left.next 
            else:h.next,right = right,right.next 
            h = h.next 

        h.next = left if left else right 
        return res.next

88. 合并两个有序数组

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        sorted = []
        p1,p2 = 0,0
        while p1 < m or p2 < n:
            if p1 == m:
                sorted.append(nums2[p2])
                p2 += 1
            elif p2 == n:
                sorted.append(nums1[p1])
                p1 += 1
            elif nums1[p1] < nums2[p2]:
                sorted.append(nums1[p1])
                p1 += 1
            else:
                sorted.append(nums2[p2])
                p2 += 1
        nums1[:] = sorted

25. K 个一组翻转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverse(self,head,tail):
        prev = tail.next
        p = head 
        while prev != tail:
            p_next = p.next 
            p.next = prev 
            prev = p 
            p = p_next 
        return tail,head 

    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        head_prev = ListNode(0)
        head_prev.next = head 
        pre = head_prev
        while head:
            tail = pre 
            for i in range(k):
                tail = tail.next 
                if not tail:
                    return head_prev.next 
            nex = tail.next 
            head,tail = self.reverse(head,tail)
            pre.next = head 
            tail.next = nex 
            pre = tail 
            head = tail.next 
        return head_prev.next 
            

78. 子集

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subs = [[]]
        for num in nums:
            newsub = []
            for sub in subs:
                new_sub = sub + [num]
                newsub.append(new_sub)
            subs.extend(newsub)
        return subs
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,684评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,143评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,214评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,788评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,796评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,665评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,027评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,679评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,346评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,664评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,766评论 1 331
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,412评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,015评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,974评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,073评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,501评论 2 343

推荐阅读更多精彩内容