240. Search a 2D Matrix II
題目網址:https://leetcode.cn/problems/search-a-2d-matrix-ii/
題意:設計一高效演算法來搜索 m x n matrix 中是否存在整數 target, matrix 滿足以下特性:
每行的元素由上到下按升序排列
每列的元素由左到右按升序排列
Solution 1:
想法:對每一列做 Binary Search, 判斷 target 是否在該列中,從而判斷 target 是否出現
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { const int m = matrix.size(), n = matrix[0].size(); for (int row = 0; row < m; ++row) { int left = 0, right = n; while ( ...
658. Find K Closest Elements
題目網址:https://leetcode.cn/problems/find-k-closest-elements/
題意:給一已排序的 array arr 以及兩整數 k 和 x, 從 arr 中找到最接近 x 的 k 個數。返回的 array 必須是已排序好的。
整數 a 比整數 b 更接近 x 須滿足:
|a - x| < |b - x|(a 比 b 更靠近 x) 或
|a - x| == |b - x| 且 a < b(兩者到 x 的距離相等, 但 a 比 b 小)
Solution 1:
想法:由於 arr 是有序的, 所以最後返回的 k 個元素也一定是有序的, 其實就是返回了原 array 中的一個長度為 k 的 subarray。實際上相當於在長度為 n 的 array 中去掉 n - k 個數字, 而且去掉的順序肯定是從兩頭開始, 因為距離 x 最遠的數字肯定在首尾出現。
➔ 每次比較首尾兩個數字跟 x 的距離, 並刪除距離較大的數字, 直到剩餘的 array 長度為 k 為止
class Solution {public: ve ...
209. Minimum Size Subarray Sum
題目網址:https://leetcode.cn/problems/minimum-size-subarray-sum/
題意:給一正整數 array nums 和一正整數 target, 返回滿足元素和 ≥ target 的長度最小的連續 subarray, 如果不存在這樣的 subarray 則返回 0。
進階:設計 $O(n \cdot log(n))$ time 和 $O(n)$ time 的演算法
Solution:
想法:利用 Sliding Window
先擴大窗口, 直到窗口裡的元素總和 sum ≥ target
此時, 開始縮小窗口, 並同時更新 res, 直到 sum < target
重複上述步驟, 直到 right 到 nums 的結尾
class Solution {public: int minSubArrayLen(int target, vector<int>& nums) { int left = 0, right = 0; const int n = num ...
904. Fruit Into Baskets
題目網址:https://leetcode.cn/problems/fruit-into-baskets/
題意:有一農場種植了一排果樹, 用 fruits 表示, 其中 fruits[i] 代表第 i 棵樹的水果種類。
農場主人設立了一些規矩, 你必須按照規矩採收:
你只有兩個籃子, 每個籃子只能裝單一種類的水果。每個籃子能裝的水果總量沒有限制。
可以選擇任一棵樹開始採收, 你必須從每棵樹上恰摘一個水果。採收的水果須符合籃子中的水果種類。每採一次, 就要往右移動到下一棵樹繼續採收。
一旦某棵樹的水果不符合籃子中的種類, 就必須停止採收。
返回可以採收的水果的最大數目。
Solution:
想法: 利用 Sliding Window
先擴大窗口, 直到 window 中的種類超過 2 種(window.size() > 2)
此時, 開始縮小窗口, 直到 window.size() == 2。注意:當某個種類的個數為 0 時, 要將其從 window 中移除, 不然 window.size() 無法減少
跳出內層 while loop 時, 代表 window.siz ...
767. Reorganize String
題目網址:https://leetcode.cn/problems/reorganize-string/
題意:給一 string s, 重新建構 s 使得相鄰的 char 不同。
返回 s 任何可能的排列。若不可行, 則返回 ""。
Solution:
想法:利用 Heap, 若有 char 的出現次數超過 $\dfrac{n+1}{2}$, 則不可能存在相鄰 char 不同的 string
建立 max heap
每次從 heap 中取兩個 top, 保證這兩個 char 必不相同
取出 top 後, 其 count - 1 若 > 0, 將其 push 回 heap 中
跳出 while loop 是因為 pq.size() < 2
若 pq.size() == 1:s 要加上 pq.top()
若 pq.size() == 0:直接返回 s
class Solution {public: string reorganizeString(string s) { unordered_map< ...