File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 1758. 生成交替二进制字符串的最少操作数
2+
3+ > ** 日期** :2026-03-05
4+ > ** 所用时间** :6min
5+ > ** 知识点** :模拟、贪心
6+
7+ ## 1. 只有两种情况
8+
9+ 交替字符串只有两种可能:从下标 0 起为 ` 0101... ` (偶数位为 0、奇数位为 1)或 ` 1010... ` (偶数位为 1、奇数位为 0)。分别统计将 ` s ` 变成这两种目标时需要的修改次数,取较小值即可。遍历时对下标 ` i ` 判断 ` s[i] ` 是否与目标相同,不同则计数加一。
10+
11+ 复杂度分析:
12+
13+ - 时间复杂度:$O(n)$,一次遍历。
14+ - 空间复杂度:$O(1)$。
15+
16+ ** Python3**
17+
18+ ``` python
19+ class Solution :
20+ def minOperations (self , s : str ) -> int :
21+ ans0 = ans1 = 0
22+
23+ for i, c in enumerate (s):
24+ if i % 2 == 0 :
25+ ans0 += int (c != ' 0' )
26+ ans1 += int (c != ' 1' )
27+ else :
28+ ans0 += int (c != ' 1' )
29+ ans1 += int (c != ' 0' )
30+ return min (ans0, ans1)
31+ ```
Original file line number Diff line number Diff line change 1- # [ LCR 076. 数组中的第 K 个最大元素] ( https://leetcode.cn/problems/xx4gT2/description/ )
1+ # LCR 076. 数组中的第 K 个最大元素
22
3- > ** 日期** :2024-12-23
4- > ** 所用时间** :1min
3+ > ** 日期** :2024-12-23、2026-03-05
4+ > ** 所用时间** :12min
5+ > ** 知识点** :排序、快速选择
56
6- ## 1. 排序
7+ ## 1. 库函数排序
78
89最简单的做法就是将整个数组排序后返回倒数第 $k$ 个元素即可。
910
1617class Solution :
1718 def findKthLargest (self , nums : List[int ], k : int ) -> int :
1819 return sorted (nums)[- k]
20+ ```
21+
22+ ## 2. 快速选择(基于快排划分)
23+
24+ 利用快排的 partition:每次划分后若枢轴下标等于 ` n - k ` ,则枢轴即为第 k 大,否则只递归一侧。期望时间复杂度 $O(n)$,最坏 $O(n^2)$;空间 $O(\log n)$ 递归栈。
25+
26+ ** Python3**
27+
28+ ``` python
29+ class Solution :
30+ def findKthLargest (self , nums : List[int ], k : int ) -> int :
31+ n = len (nums)
32+
33+ def parititon (l , r ):
34+ i, j = l, r
35+ while i < j:
36+ while i < j and nums[i] <= nums[r]:
37+ i += 1
38+ while i < j and nums[j] >= nums[r]:
39+ j -= 1
40+ if i < j:
41+ nums[i], nums[j] = nums[j], nums[i]
42+ else :
43+ nums[i], nums[r] = nums[r], nums[i]
44+ return i
45+
46+ def quick_sort (l , r ):
47+ if l < r:
48+ mid = parititon(l, r)
49+ if mid == n - k:
50+ return
51+ quick_sort(l, mid - 1 )
52+ quick_sort(mid + 1 , r)
53+ quick_sort(0 , n - 1 )
54+ return nums[n - k]
1955```
Original file line number Diff line number Diff line change 1- # [ LCR 010. 和为 K 的子数组] ( https://leetcode.cn/problems/QTMn0o/description/ )
1+ # LCR 010. 和为 K 的子数组
22
3- > ** 日期** :2024-10-11
4- > ** 所用时间** :11min
3+ > ** 日期** :2024-10-11、2026-03-05
4+ > ** 所用时间** :11min
5+ > ** 知识点** :前缀和、哈希表
56
67## 1. 前缀和
78
You can’t perform that action at this time.
0 commit comments