美文网首页
高频算法题

高频算法题

作者: wenyilab | 来源:发表于2021-05-25 09:05 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:高频算法题

          本文链接:https://www.haomeiwen.com/subject/oiitsltx.html