Week7-LeetCode

2024-04-18 15:04
文章标签 leetcode week7

本文主要是介绍Week7-LeetCode,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

2923.找到冠军(简单)

法1:

class Solution:def findChampion(self, grid: List[List[int]]) -> int:Winner = 0n = len(grid)loser = [0 for _ in range(n)] for i in range(n):for j in range(n):if grid[i][j] == 1 and i != j:loser[j] = 1for index in range(n):if loser[index] == 0:return index

法2:

class Solution:def findChampion(self, grid: List[List[int]]) -> int:n = len(grid)for i, line in enumerate(grid):if sum(line) == n - 1:return i

22.括号生成(中等)

思路1→暴力法:
把所有可能的组合列出,去除不合格的可能。

class Solution:def generateParenthesis(self, n: int) -> List[str]:def generate(A):if len(A) == 2 * n:if valid(A):ans.append("".join(A))else:A.append('(')generate(A)A.pop()A.append(')')generate(A)A.pop()def valid(A):bal = 0for c in A:if c =='(':bal += 1else: bal -= 1if bal < 0:return Falsereturn bal == 0ans = []generate([])return ans

思路2→回溯法:
对思路1进行改进,我们可以只在序列仍然保持有效时才添加 ‘(’‘)’,而不是每次添加。我们可以通过跟踪到目前为止放置的左括号和右括号的数目来做到这一点。

class Solution:def generateParenthesis(self, n: int) -> List[str]:ans = []def backtrack(S, left, right):if len(S) == 2 * n:ans.append(''.join(S))return if left < n:S.append('(')backtrack(S, left + 1, right)S.pop()if right < left:S.append(')')backtrack(S, left, right + 1)S.pop()backtrack([], 0, 0)return ans

思路3→递归法:

class Solution:@lru_cache(None)def generateParenthesis(self, n: int) -> List[str]:if n == 0:return ['']ans = []for c in range(n):for left in self.generateParenthesis(c):for right in self.generateParenthesis(n - 1 - c):ans.append('({}){}'.format(left, right))return ans

23. 合并K个升序链表(困难)

思路:
把链表元素全部加到数组中,对数组排序,然后将数组元素组成链表。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:nums = []head = ListNode(0)current = headfor li in lists:while li:nums.append(li.val)li = li.nextnums.sort()for num in nums:current.next = ListNode(num)current = current.nextreturn head.next

2924. 找到冠军 II (中等)

思路:
把所有节点的degree值设为0,意为没输过,如果遍历到一个节点没输过,且当前没有冠军节点,那么这个节点就是冠军,否则就是没有冠军。

class Solution:def findChampion(self, n: int, edges: List[List[int]]) -> int:degree = [0] * n for x, y in edges:degree[y] += 1champion = -1for i, d in enumerate(degree):if d == 0:if champion == -1:champion = ielse:return -1return champion

24.两两交换链表中的节点 (中等)

关键思路:
需要额外的节点来记录prev, cur, temp, next

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:if head == None or head.next == None:return headtemp = ListNode(0)next_one = ListNode(0)prev = ListNode(0)newhead = ListNode(0)newhead.next = headprev = newheadcur = headwhile cur != None and cur.next != None:next_one = cur.next.nexttemp = cur.nextcur.next = temp.nexttemp.next = curprev.next = tempprev = curcur = next_onereturn newhead.next

25. K 个一组翻转链表(困难)

关键思路:
分为两个函数去实现:
函数1:把K个链表全部倒转,需要四个辅助指针。
函数2:找到K个链表,把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:ListNode, tail:ListNode):prev = tail.nextp = headwhile prev != tail:nex = p.nextp.next = prevprev = pp = nexreturn tail, head   def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:hair = ListNode(0)hair.next = headpre = hairwhile head:tail = pre# 查看剩余部分长度是否大于等于 kfor i in range(k):tail = tail.nextif not tail:return hair.nextnex = tail.nexthead, tail = self.reverse(head, tail)# 把子链表重新接回原链表pre.next = headtail.next = nexpre = tailhead = tail.nextreturn hair.next

26.删除有序数组中的重复项(简单)

class Solution:def removeDuplicates(self, nums: List[int]) -> int:n = len(nums)index = 0for i in range(1, n):if nums[i] != nums[index]:index += 1nums[index] = nums[i]return index + 1

27. 移除元素 (简单)

class Solution:def removeElement(self, nums: List[int], val: int) -> int:index = 0for i in range(len(nums)):if nums[i] != val:nums[index] = nums[i]index += 1return index

28. 找出字符串中第一个匹配项的下标 (简单)

class Solution:def strStr(self, haystack: str, needle: str) -> int:h = len(haystack)n = len(needle)i = 0index = 0while i <= h - n:for j in range(n):if haystack[i + j] == needle[j]:index += 1if index == n:return iindex = 0i += 1return -1

29. 两数相除 (中等)

关键思路:
为方便运算,将除数和被除数的符号统一;又为了不溢出,故将除数和被除数变为负数。
同样,在运算过程中为了避免溢出,把 A+B < C 的比较换为 A < C - B

class Solution:def divide(self, dividend: int, divisor: int) -> int:INT_MIN, INT_MAX = -2**31, 2 ** 31 - 1if dividend == INT_MIN:if divisor == 1:return INT_MINif divisor == -1:return INT_MAXif divisor == INT_MIN:return 1 if dividend == INT_MIN else 0if dividend == 0:return 0rev = Falseif dividend > 0:dividend = -dividendrev = not revif divisor > 0 :divisor = -divisorrev = not revdef quickAdd(y:int, z:int, x:int) -> bool:result, add = 0, ywhile z > 0:if (z & 1) == 1:if result < x - add:return Falseresult += addif z != 1:if add < x - add:return Falseadd += add  z >>= 1return Trueleft, right, ans = 1, INT_MAX, 0while left <= right:# 注意溢出,并且不能使用除法mid = left + ((right - left) >> 1)check = quickAdd(divisor, mid, dividend)if check:ans = mid# 注意溢出if mid == INT_MAX:breakleft = mid + 1else:right = mid - 1return -ans if rev else ans

这篇关于Week7-LeetCode的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/915111

相关文章

哈希leetcode-1

目录 1前言 2.例题  2.1两数之和 2.2判断是否互为字符重排 2.3存在重复元素1 2.4存在重复元素2 2.5字母异位词分组 1前言 哈希表主要是适合于快速查找某个元素(O(1)) 当我们要频繁的查找某个元素,第一哈希表O(1),第二,二分O(log n) 一般可以分为语言自带的容器哈希和用数组模拟的简易哈希。 最简单的比如数组模拟字符存储,只要开26个c

leetcode-24Swap Nodes in Pairs

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode swapPairs(L

leetcode-23Merge k Sorted Lists

带头结点。 /*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/public class Solution {public ListNode mergeKLists

C++ | Leetcode C++题解之第393题UTF-8编码验证

题目: 题解: class Solution {public:static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num &

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟)

【每日一题】LeetCode 2181.合并零之间的节点(链表、模拟) 题目描述 给定一个链表,链表中的每个节点代表一个整数。链表中的整数由 0 分隔开,表示不同的区间。链表的开始和结束节点的值都为 0。任务是将每两个相邻的 0 之间的所有节点合并成一个节点,新节点的值为原区间内所有节点值的和。合并后,需要移除所有的 0,并返回修改后的链表头节点。 思路分析 初始化:创建一个虚拟头节点

C语言 | Leetcode C语言题解之第393题UTF-8编码验证

题目: 题解: static const int MASK1 = 1 << 7;static const int MASK2 = (1 << 7) + (1 << 6);bool isValid(int num) {return (num & MASK2) == MASK1;}int getBytes(int num) {if ((num & MASK1) == 0) {return

【JavaScript】LeetCode:16-20

文章目录 16 无重复字符的最长字串17 找到字符串中所有字母异位词18 和为K的子数组19 滑动窗口最大值20 最小覆盖字串 16 无重复字符的最长字串 滑动窗口 + 哈希表这里用哈希集合Set()实现。左指针i,右指针j,从头遍历数组,若j指针指向的元素不在set中,则加入该元素,否则更新结果res,删除集合中i指针指向的元素,进入下一轮循环。 /*** @param

LeetCode:64. 最大正方形 动态规划 时间复杂度O(nm)

64. 最大正方形 题目链接 题目描述 给定一个由 0 和 1 组成的二维矩阵,找出只包含 1 的最大正方形,并返回其面积。 示例1: 输入: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0输出: 4 示例2: 输入: 0 1 1 0 01 1 1 1 11 1 1 1 11 1 1 1 1输出: 9 解题思路 这道题的思路是使用动态规划

LeetCode 第414场周赛个人题解

目录 Q1. 将日期转换为二进制表示 原题链接 思路分析 AC代码 Q2. 范围内整数的最大得分 原题链接 思路分析 AC代码 Q3. 到达数组末尾的最大得分 原题链接 思路分析 AC代码 Q4. 吃掉所有兵需要的最多移动次数 原题链接 思路分析 AC代码 Q1. 将日期转换为二进制表示 原题链接 Q1. 将日期转换为二进制表示 思路分析

【JavaScript】LeetCode:21-25

文章目录 21 最大子数组和22 合并区间23 轮转数组24 除自身以外数组的乘积25 缺失的第一个正数 21 最大子数组和 贪心 / 动态规划贪心:连续和(count)< 0时,放弃当前起点的连续和,将下一个数作为新起点,这里提供使用贪心算法解决本题的代码。动态规划:dp[i]:以nums[i]为结尾的最长连续子序列(子数组)和。 dp[i] = max(dp[i - 1]