Week1-3 LeetCode(共20道题)

2024-03-20 22:12
文章标签 leetcode 20 道题 week1

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

1. 两数之和 (简单)

class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""# 创字典记录:在就返回target-num的下标和i 不在就把i加入字典hashtable = dict()for i, num in enumerate(nums):if target - num in hashtable:return [hashtable[target - num], i]hashtable[nums[i]] = ireturn []

225. 用队列实现栈 (简单)

class MyStack(object):def __init__(self):self.queue1 = []self.queue2 = []def push(self, x):""":type x: int:rtype: None"""# 空的队进新元素,然后把不空的队列的元素放到刚刚添加新元素的队if not self.queue1:self.queue1.append(x)while self.queue2:self.queue1.append(self.queue2.pop(0))else:self.queue2.append(x)while self.queue1:self.queue2.append(self.queue1.pop(0))def pop(self):""":rtype: int"""if self.queue1:return self.queue1.pop(0)elif self.queue2:return self.queue2.pop(0)else:return Nonedef top(self):""":rtype: int"""if self.queue1:return self.queue1[0]elif self.queue2:return self.queue2[0]else:return Nonedef empty(self):""":rtype: bool"""return not(self.queue1) and not(self.queue2)# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

232.用栈实现队列 (简单)

class MyQueue(object):def __init__(self):self.stack1 = []self.stack2 = []def push(self, x):self.stack1.append(x)def pop(self):if not self.stack2:while self.stack1:self.stack2.append(self.stack1.pop())return self.stack2.pop()def peek(self):if not self.stack2:while self.stack1:self.stack2.append(self.stack1.pop())return self.stack2[-1]def empty(self):return not self.stack1 and not self.stack2

2917. 找出数组中的 K-or 值 (简单)

class Solution(object):def findKOr(self, nums, k):""":type nums: List[int]:type k: int:rtype: int"""# 枚举数组nums中元素nums[j]ans = 0for i in range(31):cnt = sum(1 for num in nums if ((num >> i) & 1) > 0)if cnt >= k:ans |= 1 << i  # 将ans的第i位设置为1   (将二进制数1左移i位,然后与ans执行按位或操作)return ans

2129.将标题首字母大写 (简单)

class Solution(object):def capitalizeTitle(self, title):""":type title: str:rtype: str"""res = []for word in title.split():if len(word) <= 2:res.append(word.lower())else:res.append(word[0].upper() + word[1:].lower())return ' '.join(res)

2864.最大二进制奇数 (简单)

class Solution(object):def maximumOddBinaryNumber(self, s):""":type s: str:rtype: str"""cnt = s.count('1')return '1' * (cnt - 1) + '0' * (len(s) - cnt) + '1'

2.两数相加 (中等)

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):def addTwoNumbers(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""carry = 0head = ListNode()current = headwhile l1 or l2 or carry:x = l1.val if l1 else 0y = l2.val if l2 else 0current_sum = x + y + carrycarry = current_sum // 10current_digit = current_sum % 10current.next = ListNode(current_digit)current = current.nextif l1:l1 = l1.nextif l2:l2 = l2.nextreturn head.next

3.无重复字符的最长子串 (中等)

class Solution(object):def lengthOfLongestSubstring(self, s):""":type s: str:rtype: int"""charIndex = {} # 存储字符及其最后出现的位置left = 0 max_length = 0for i in range(len(s)):if s[i] in charIndex and charIndex[s[i]] >= left:left = charIndex[s[i]] + 1 # 更新窗口的起始位置charIndex[s[i]] = i # 更新字符的最后出现位置current_length = i - left + 1 # 计算当前窗口的长度max_length = max(max_length, current_length)return max_length

6. Z 字形变换 (中等)

class Solution(object):def convert(self, s, numRows):""":type s: str:type numRows: int:rtype: str"""if numRows < 2:return sres = ["" for _ in range(numRows)] # 创建了一个包含 numRows 个空字符串的列表i, flag = 0, -1for c in s:res[i] += cif i == 0 or i == numRows - 1:flag = -flagi += flagreturn  "".join(res)

7. 整数反转(中等)

class Solution(object):def reverse(self, x):""":type x: int:rtype: int"""rev = 0Min, Max = -2**31, 2**31 - 1 # 重点:需要判断反转后的数字是否超过 32 位有符号整数的范围while x != 0:if rev < Min // 10 + 1 or  rev > Max // 10:return 0digit = x % 10if x < 0 and digit > 0:digit -= 10x = (x - digit) // 10rev = rev * 10 + digitreturn rev

1976.到达目的地的方案数 (中等)

class Solution(object):def countPaths(self, n, roads):""":type n: int:type roads: List[List[int]]:rtype: int"""mod = 10 ** 9 + 7graph = {i : [] for i in range(n)}for road in roads:u, v, time = roadgraph[u].append((v, time))graph[v].append((u, time))dist = [float('inf')] * nways = [0] * ndist[0] = 0ways[0] = 1heap = [(0, 0)] #(time, node)while heap:curr_time, curr_node = heapq.heappop(heap)if curr_time > dist[curr_node]:continuefor neighbor, time in graph[curr_node]:if dist[curr_node] + time < dist[neighbor]:dist[neighbor] = dist[curr_node] + timeways[neighbor] = ways[curr_node]heapq.heappush(heap, (dist[neighbor], neighbor))elif dist[curr_node] + time == dist[neighbor]:ways[neighbor] = (ways[neighbor] + ways[curr_node]) % modreturn ways[-1]

2575.找出字符串的可整除数组 (中等)

class Solution(object):def divisibilityArray(self, word, m):""":type word: str:type m: int:rtype: List[int]"""cur = 0res = []for c in word:cur = (cur * 10 + int(c)) % mres.append(1 if cur == 0 else 0)return res

2576. 求出最多标记下标 (中等)

class Solution(object):def maxNumOfMarkedIndices(self, nums):""":type nums: List[int]:rtype: int"""# 思路:# 假设存在k对匹配# 那么 nums[i] 一定要匹配 nums[n - k + i]# 如果对于所有的 0 <= i <k 都有 2 * nums[i] <= nums[n - k + i]# 那么可以匹配k对nums.sort()left, right = 0, len(nums) // 2 + 1 # 开区间while left + 1 < right:k = (left + right) // 2if all(nums[i] * 2 <= nums[i - k] for i in range(k)):left = kelse:right = kreturn left * 2

2834. 找出美丽数组的最小和 (中等)

class Solution(object):def minimumPossibleSum(self, n, target):""":type n: int:type target: int:rtype: int"""# 使用贪心算法# 为使得数组之和最小,按照1, 2, 3...的顺序考虑# 添加了 x 之后, 就不能添加target - x# 最大可以添加到 target / 2 # 如果个数不够,继续从target, target + 1, target + 2, ... 依次添加# 两种情况# 1. n <= target / 2 # 最小数组和为 (1+n) * n / 2# 2. n > target / 2  等差数列 求和# 最小数组和为 (1 + target / 2) * target / 2 / 2  + (target + (target + (n - target / 2) - 1)) * (n - target) / 2mod = 10 ** 9 + 7m = target // 2if n <= m :return ((1 + n) * n // 2) % modreturn ((1 + m) * m // 2 + (n - m) * (target + (target + (n - m) - 1))  // 2 ) % mod

1261. 在受污染的二叉树中查找元素 (中等)

class FindElements(object):def __init__(self, root):""":type root: TreeNode"""root.val = 0self.values = set()def dfs(node):if not node:return self.values.add(node.val)if node.left:node.left.val = 2 * node.val + 1dfs(node.left)if node.right:node.right.val = 2 * node.val + 2dfs(node.right)dfs(root)def find(self, target):""":type target: int:rtype: bool"""return target in self.values

2789.合并后数组中的最大元素 (中等)

class Solution(object):def maxArrayValue(self, nums):""":type nums: List[int]:rtype: int"""for i in range(len(nums) - 2, -1, -1):if nums[i] <= nums[i + 1]:nums[i] += nums[i + 1]return nums[0]

5. 最长回文子串 (中等)

class Solution(object):def expandAroundCenter(self, s, left, right):while left >= 0 and right < len(s) and s[left] == s[right]:left -= 1right += 1return  left + 1, right -1def longestPalindrome(self, s):""":type s: str:rtype: str"""start, end = 0, 0for i in range(len(s)):left1, right1 = self.expandAroundCenter(s, i, i)left2, right2 = self.expandAroundCenter(s, i, i + 1)if right1 - left1 > end - start:start, end = left1, right1if right2 - left2 > end - start:start, end = left2, right2return s[start: end + 1]

4.寻找两个正序数组的中位数 (困难)

class Solution(object):def findMedianSortedArrays(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: float"""nums = nums1 + nums2nums.sort()mid = len(nums) // 2if len(nums) % 2 == 0:return (nums[mid] + nums[mid - 1]) / 2.0else:return (nums[mid])

2312. 卖木头块 (困难)

class Solution:def sellingWood(self, m, n, prices):h_ps = sorted(list(set([i[0] for i in prices])))w_ps = sorted(list(set([i[1] for i in prices])))dps = [[None] * (n+1) for _ in range(m+1)]hw2p = dict()for h, w, p in prices:hw2p[(h, w)] = pdef func(h, w):if dps[h][w] is None:if h == 0 or w == 0:dps[h][w] = 0else:if (h, w) in hw2p:max_ps = hw2p[(h, w)]else:max_ps = 0for ht in h_ps:if ht >= h:breakelse:ps = func(h - ht, w) + func(ht, w)if ps > max_ps:max_ps = psfor wt in w_ps:if wt >= w:breakelse:ps = func(h, w - wt) + func(h, wt)if ps > max_ps:max_ps = psdps[h][w] = max_psreturn dps[h][w]return func(m, n)

2386.返回数组的第k大和 (困难)

class Solution(object):def kSum(self, nums, k):""":type nums: List[int]:type k: int:rtype: int"""n = len(nums)total = 0for i in range(n):if nums[i] >= 0:total += nums[i]else:nums[i] = -nums[i]nums.sort()ret = 0pq = [(nums[0], 0)]for j in range(2, k + 1):t, i = heappop(pq)ret = tif i == n - 1:continueheappush(pq, (t + nums[i + 1], i + 1))heappush(pq, (t - nums[i] + nums[i + 1], i + 1))return total - ret

这篇关于Week1-3 LeetCode(共20道题)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

哈希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

系统架构师考试学习笔记第三篇——架构设计高级知识(20)通信系统架构设计理论与实践

本章知识考点:         第20课时主要学习通信系统架构设计的理论和工作中的实践。根据新版考试大纲,本课时知识点会涉及案例分析题(25分),而在历年考试中,案例题对该部分内容的考查并不多,虽在综合知识选择题目中经常考查,但分值也不高。本课时内容侧重于对知识点的记忆和理解,按照以往的出题规律,通信系统架构设计基础知识点多来源于教材内的基础网络设备、网络架构和教材外最新时事热点技术。本课时知识

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

【C++学习笔记 20】C++中的智能指针

智能指针的功能 在上一篇笔记提到了在栈和堆上创建变量的区别,使用new关键字创建变量时,需要搭配delete关键字销毁变量。而智能指针的作用就是调用new分配内存时,不必自己去调用delete,甚至不用调用new。 智能指针实际上就是对原始指针的包装。 unique_ptr 最简单的智能指针,是一种作用域指针,意思是当指针超出该作用域时,会自动调用delete。它名为unique的原因是这个

【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 解题思路 这道题的思路是使用动态规划