LeetCode 二分查找
文章目录
- [0378. 有序矩阵中第K小的元素 [Medium] [Kth Smallest Element in a Sorted Matrix]](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/)
- [0441. 排列硬币 [Easy] [Arranging Coins]](https://leetcode.com/problems/arranging-coins/)
- [0410. 分割数组的最大值 [Hard] [Split Array Largest Sum]](https://leetcode.com/problems/split-array-largest-sum/)
- [0875. 爱吃香蕉的珂珂 [Medium] [Koko Eating Bananas]](https://leetcode.com/problems/koko-eating-bananas/)
- [1011. 在 D 天内送达包裹的能力 [Medium] [Capacity To Ship Packages Within D Days]](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)
- [1283. 使结果不超过阈值的最小除数 [Medium] [Find the Smallest Divisor Given a Threshold]](https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/)
- [1760. 袋子里最少数目的球 [Medium] [Minimum Limit of Balls in a Bag]](https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/)
- [1870. 准时到达的列车最小时速 [Medium] [Minimum Speed to Arrive on Time]](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/)
- [2064. 分配给商店的最多商品的最小值 [Medium] [Minimized Maximum of Products Distributed to Any Store]](https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/)
- [2187. 完成旅途的最少时间 [Medium] [Minimum Time to Complete Trips]](https://leetcode.com/problems/minimum-time-to-complete-trips/)
0378. 有序矩阵中第K小的元素 [Medium] [Kth Smallest Element in a Sorted Matrix]
Note that it is the kth
smallest element in the sorted order, not the kth
distinct element.
You must find a solution with a memory complexity better than O(n^2)
.
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Input: matrix = [[-5]], k = 1
Output: -5
n == matrix.length == matrix[i].length
1 <= n <= 300
-10^9 <= matrix[i][j] <= 10^9
- All the rows and columns of
matrix
are guaranteed to be sorted in non-decreasing order. 1 <= k <= n^2
- Could you solve the problem with a constant memory (i.e.,
O(1)
memory complexity)? - Could you solve the problem in
O(n)
time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
**思路:**二分查找link,在[matrix[0][0], matrix[m-1][n-1] + 1)
中二分查找目标值。
class Solution {public:int kthSmallest(vector<vector<int>>& matrix, int k) {int m = matrix.size();int n = matrix[0].size();int lo = matrix[0][0], hi = matrix[m-1][n-1] + 1;while(lo < hi){int mid = (lo + hi)/2;int cnt = 0, j = m-1;for(int i = 0; i < n; ++i){while(j >= 0 && matrix[i][j] > mid)--j;cnt += j + 1;}// 保证最后的lo一定为数组中的元素if(cnt < k)lo = mid + 1;elsehi = mid;}return lo;}
};
struct Tuple{public:int x;int y;int val;Tuple(int x, int y, int val):x(x), y(y), val(val){}
};struct CmpVal{bool operator() (const Tuple& t1, const Tuple& t2){return t1.val > t2.val; // 小顶堆}
};class Solution {public:int kthSmallest(vector<vector<int>>& matrix, int k) {priority_queue<Tuple, vector<Tuple>, CmpVal> pq;int r = matrix.size();int c = r > 0 ? matrix[0].size() : 0;for(int j = 0; j < c; ++j)pq.push(Tuple(0, j, matrix[0][j]));for(int i = 1; i < k; ++i){Tuple t = pq.top();pq.pop();if(t.x >= r-1)continue;pq.push(Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y]));}return pq.top().val;}
};
0441. 排列硬币 [Easy] [Arranging Coins]
Given the integer n
, return the number of complete rows of the staircase you will build.
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.
class Solution {public:int arrangeCoins(int n) {long l = 1, r = (long)n + 1;int res = 0;while(l < r){long mid = l + (r - l)/2;long cnt = (1 + mid)*mid/2;if(cnt <= n){l = mid + 1;res = mid;}elser = mid;}return res;}
};
0410. 分割数组的最大值 [Hard] [Split Array Largest Sum]
Write an algorithm to minimize the largest sum among these m
subarrays.
Input: nums = [7,2,5,10,8], m = 2
Output: 18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
Input: nums = [1,2,3,4,5], m = 2
Output: 9
Input: nums = [1,4,4], m = 3
Output: 4
题目:给定一个非负整数数组 nums
和一个整数 m
,你需要将这个数组分成 m
个非空的连续子数组。设计一个算法使得这 m
个子数组各自和的最大值最小。
思路:二分法。假设最终求的结果为res
,可知其在范围[max(nums), sum(nums)+1)
中。当子串和的上限为mid
时,计算其对应的子串数目cnt
;与题目中对应的m
比较,更改搜索范围。
class Solution {public:int splitArray(vector<int>& nums, int m) {int lo = 0, hi = 1;for(int num : nums){lo = max(lo, num);hi += num;}while(lo < hi){int mid = lo + (hi-lo)/2;int cnt = 1, sum = 0;for(int num : nums){sum += num;if(sum > mid){cnt += 1;sum = num;}}if(cnt > m)lo = mid + 1;elsehi = mid;}return lo;}
};
0875. 爱吃香蕉的珂珂 [Medium] [Koko Eating Bananas]
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer k
such that she can eat all the bananas within h
hours.
Input: piles = [3,6,7,11], h = 8
Output: 4
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Input: piles = [30,11,23,4,20], h = 6
Output: 23
思路:二分法,同1011. Capacity To Ship Packages Within D Days。
class Solution {public:int minEatingSpeed(vector<int>& piles, int h) {int lo = 1, hi = 1e9 + 1;while(lo < hi){int mid = lo + (hi - lo) / 2; // eating speedint cnt = 0;for(int p : piles){cnt += (p + mid - 1) / mid;}if(cnt > h)lo = mid + 1;elsehi = mid;}return lo;}
};
1011. 在 D 天内送达包裹的能力 [Medium] [Capacity To Ship Packages Within D Days]
A conveyor belt has packages that must be shipped from one port to another within D
days.
Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
思路:同LeetCode410. Split Array Largest Sum
class Solution {public:int shipWithinDays(vector<int>& weights, int days) {int lo = 1, hi = 1;for(int w : weights){lo = max(lo, w);hi += w;}while(lo < hi){int mid = (lo + hi) / 2; // Capacityint d = 1, sum = 0;for(int w : weights){sum += w;if(sum > mid){sum = w;d += 1;}}if(d > days)lo = mid + 1;elsehi = mid;}return lo;}
};
1283. 使结果不超过阈值的最小除数 [Medium] [Find the Smallest Divisor Given a Threshold]
The test cases are generated so that there will be an answer.
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Input: nums = [44,22,33,11,1], threshold = 5
Output: 44
class Solution {public:int smallestDivisor(vector<int>& nums, int threshold) {int lo = 1, hi = 1e6 + 1;while(lo < hi){int mid = (lo + hi) / 2;int sum = 0;for(int num : nums)sum += (num + mid - 1) / mid;if(sum > threshold)lo = mid + 1;elsehi = mid;}return lo;}
};
1760. 袋子里最少数目的球 [Medium] [Minimum Limit of Balls in a Bag]
You can perform the following operation at most maxOperations
times:
Take any bag of balls and divide it into two new bags with a positive number of balls.
- For example, a bag of
5
balls can become two new bags of1
and4
balls, or two new bags of2
and3
balls.
- For example, a bag of
Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.
Return the minimum possible penalty after performing the operations.
Example 1:
Input: nums = [9], maxOperations = 2
Output: 3
Explanation:
- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].
- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].
The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
Example 2:
Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
Explanation:
- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].
The bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.
Example 3:
Input: nums = [7,17], maxOperations = 2
Output: 7
Constraints:
1 <= nums.length <= 10^5
1 <= maxOperations, nums[i] <= 10^9
题目:给你一个整数数组 nums
,其中 nums[i]
表示第 i
个袋子里球的数目。同时给你一个整数 maxOperations
。你可以进行如下操作至多 maxOperations
次:选择任意一个袋子,并将袋子里的球分到 2 个新的袋子中,每个袋子里都有 正整数 个球。比方说,一个袋子里有 5
个球,你可以把它们分到两个新袋子里,分别有 1
个和 4
个球,或者分别有 2
个和 3
个球。你的开销是单个袋子里球数目的 最大值 ,你想要 最小化 开销。请你返回进行上述操作后的最小开销。
思路:二分查找。假设我们已经找到了最小开销为res
,那么对于某个袋子的球num
,被分至n
个新袋子,均满足个数小于等于res
,其所需的拆分操作数为cnt=(num-1)/res
。判断所有的操作数是否超过了maxOperations
,依此来调整res
。
工程代码下载
class Solution {public:int minimumSize(vector<int>& nums, int maxOperations) {int l = 1, r = 1e9;while(l < r){int mid = l + (r - l)/2;int cnt = 0;for(int num : nums){cnt += (num - 1) / mid;}if(cnt > maxOperations)l = mid + 1;elser = mid;}return l;}
};
1870. 准时到达的列车最小时速 [Medium] [Minimum Speed to Arrive on Time]
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
Input: dist = [1,3,2], hour = 6
Output: 1
Explanation: At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
Input: dist = [1,3,2], hour = 2.7
Output: 3
Explanation: At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
Input: dist = [1,3,2], hour = 1.9
Output: -1
Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.
n == dist.length
1 <= n <= 10^5
1 <= dist[i] <= 10^5
1 <= hour <= 10^9
- There will be at most two digits after the decimal point in
hour
.
思路:二分查找。由题目限制可知,可能的速度范围为[1, 10^7]
。计算当前速度达到目的地所需的时间,二分查找对应的最小速度。更多二分查找题目:link。
class Solution {public:int minSpeedOnTime(vector<int>& dist, double hour) {int l = 1, r = 1e7 + 1;int n= dist.size();while(l < r){int m = l + (r - l)/2; // speeddouble t = 0;for(int i = 0; i < n-1; ++i){t += (dist[i] + m - 1) / m;}t += (double)dist.back() / m;if(t > hour)l = m + 1;elser = m;}return r == 1e7 + 1 ? -1 : r;}
};
2064. 分配给商店的最多商品的最小值 [Medium] [Minimized Maximum of Products Distributed to Any Store]
You need to distribute all products to the retail stores following these rules:
- A store can only be given at most one product type but can be given any amount of it.
- After distribution, each store will have been given some number of products (possibly
0
). Letx
represent the maximum number of products given to any store. You wantx
to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.
Return the minimum possible x
.
Input: n = 6, quantities = [11,6]
Output: 3
Explanation: One optimal way is:
- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3
- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3
The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.
Input: n = 7, quantities = [15,10,10]
Output: 5
Explanation: One optimal way is:
- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5
- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5
- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5
The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.
Input: n = 1, quantities = [100000]
Output: 100000
Explanation: The only optimal way is:
- The 100000 products of type 0 are distributed to the only store.
The maximum number of products given to any store is max(100000) = 100000.
思路:二分查找。假设每个商店都能分到mid
个商品,计算此时是否有足够的或多余的quantities
,二分查找最小的mid
。
class Solution {public:int minimizedMaximum(int n, vector<int>& quantities) {int l = 1, r = 1e5 + 1;while(l < r){int mid = (l + r) / 2, sum = 0;for(int q : quantities)sum += (q + mid - 1) / mid;if(sum > n)l = mid + 1;elser = mid;}return l;}
};
2187. 完成旅途的最少时间 [Medium] [Minimum Time to Complete Trips]
Input: time = [1,2,3], totalTrips = 5
Output: 3
Explanation:
- At time t = 1, the number of trips completed by each bus are [1,0,0].The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0].The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1].The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
Input: time = [2], totalTrips = 1
Output: 2
Explanation:
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
class Solution {public:long long minimumTime(vector<int>& time, int totalTrips) {long long l = 1, r = 1e14 + 1;while(l < r){long long mid = l + (r -l)/2;long long cur = 0;for(int t : time)cur += mid / t;if(cur < totalTrips)l = mid + 1;elser = mid;}return l;}
};
LeetCode 二分查找相关推荐
- 七十六、Python | Leetcode二分查找和分治算法系列
@Author:Runsen @Date:2020/7/4 人生最重要的不是所站的位置,而是内心所朝的方向.只要我在每篇博文中写得自己体会,修炼身心:在每天的不断重复学习中,耐住寂寞,练就真功,不畏艰 ...
- 【LeetCode 二分查找专项】最长递增子序列(300)(to be polished...)
文章目录 1. 题目 1.1 示例 1.2 说明 1.3 提示 1.4 进阶 2. 解法一(动态规划) 2.1 分析 2.2 解答 2.3 复杂度 3. 解法二(二分查找) 3.1 分析 3.2 解答 ...
- leetcode 二分查找 Search in Rotated Sorted ArrayII
Search in Rotated Sorted Array II Total Accepted: 18500 Total Submissions: 59945My Submissions Follo ...
- LeetCode——二分查找
二分查找 目录 二分查找法 求开方 大于给定元素的最小元素 有序数组的 Single Element 第一个错误的版本 旋转数组的最小数字 查找区间 1. 二分查找法 正常实现 public int ...
- leetcode二分查找
1.猜数字进行二分查找: 2.查找两个数组之间的重复交叉项 转载于:https://www.cnblogs.com/mmziscoming/p/5777008.html
- LeetCode二分查找问题全集
文章目录 二分查找框架 704. 二分查找 33. 搜索旋转排序数组 81. 搜索旋转排序数组 II 153. 寻找旋转排序数组中的最小值 154. 寻找旋转排序数组中的最小值 II 300. 最长上 ...
- [LeetCode]704.二分查找及相关题目
数组理论基础 数组理论 数组是存放在连续内存空间上的相同类型数据的集合 数组可以方便的通过下标索引的方式获取到下标下对应的数据 二维数组在内存的空间地址是连续的 二分查找 LeetCode 704.二 ...
- LeetCode简单题之二分查找
题目 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1. 示例 1: 输入: n ...
- 「二分查找」之我见!今天刷一道leetcode算法!
来自:码农田小齐 算法将是我今后更新的重点,因为我个人非常喜欢..而且面试考它啊!有人说刷题没有用,但是你做了题就能感受到 coding 能力的提升和对语言熟悉度的提升.新的一年,每日一题,我们一起进 ...
最新文章
- (C++)一行代码递归实现辗转相除法
- WordPress插件制作教程概述
- python拼音怎么写-【学习】python 汉语转拼音
- Docker中运行命令时提示:Cannot connect to the Docker daemony...以及设置docker开机启动
- java之解析DNS的SRV记录
- android根据中心裁剪图片,拍照,选择照片并进行裁剪,适配Android 7.0
- 深入Node.js的模块机制
- pe linux系统安装教程视频教程,各种Veket安装方法及UD版PE+linux U盘制作
- STM32制作flash烧写器 spi flash
- swfupload 无法加载_解决 KindEditor SWFUpload 批量上传检测用户登录状态的问题
- resin 系统日志_resin学习随笔
- 中国知网论文破解下载 (附:常用的网址)
- 敏捷 绩效_管理敏捷团队绩效的四个技巧
- 主引导记录MBR详解
- 联发科MT6737和MT6735芯片组有什么差异?MT6737和MT6735芯片组资料分享
- Win7 设置防火墙开放特定端口
- R语言关于心脏病相关问题的预测和分析
- CDS视图的基本语法,函数以及数量,货币类型转换
- MVC详解:mvc是什么?为什么要用MVC?MVC工作原理以及MVC优缺点
- 单片机c语言报错_asm啥意思,SPMC75系列单片机地C和ASM( - 控制/MCU - 电子发烧友网...
热门文章
- 为什么这么多人转行产品经理?产品经理发展前景如何?
- 上饶临床实验室改造规划要点
- 【分布式】分布式环境下如何保证数据库和缓存的双写一致性?看完我明白了!!
- 题目:用D触发器带同步高置数和异步高复位端的二分频的电路,画出逻辑电路,Verilog描述。
- Mixly(米思齐)的安装以及实现光控小夜灯
- 巴别塔圣经_承认巴别塔
- 笔记本光驱在计算机里不显示器,笔记本怎么解决识别不了光驱
- win8通过u盘装linux系统,如何通过U盘装机大师进行U盘安装win8.1系统
- 马来西亚SIRIM认证
- mysql_connect函数怎么调用,PHP连接MySQL数据库的连接函数mysql_connect的第三个参数是( )。...