当前位置:网站首页>搜索旋转数组II[抽象二分练习]
搜索旋转数组II[抽象二分练习]
2022-06-25 22:09:00 【REN_林森】
抽象二分练习
前言
抽象二分,常见考题,以二分快速逼近的思想,抽象判断规则,实现低时间复杂度寻找target。
一、搜索旋转数组II

二、抽象二分
package everyday.medium;
// 搜索旋转排序数组II
public class Search {
/* target:一个升序数组,从下表k开始旋转得到新数组,即两个有序子数组。 所以,可以先快速找到k在那里,然后两次二分,确定target是否存在。 二分如何确定k?其实就算考察抽象二分,判断规则抽象。 定义为,midVal > nums[0],说明mid在第一个子数组,则low = mid; midVal < nums[0],说明mid进入第二个子数组中,则high = mid - 1 如果两者相等,这个值可能属于第一数组,也可能属于第二个数组。这是一个问题,无法判断。 [2,2,2,2,2,2,2,0,1,2] | [2,2,2,0,1,2,2,2,2,2,2] 破局?当左中右相等时,则不急着取mid,而是右边向左走一格,这样左边的值是回小于等于nums[high]的。 最终取到第一个数组的尾巴 i,则i+1就算最小值所在。 */
public boolean search(int[] nums, int target) {
// 二分寻k,抽象二分。
int low = 0, high = nums.length - 1;
// 二分快速找到比nums[0]小的,第一个小的。
int first = nums[0];
while (low < high) {
int mid = low + (high - low + 1 >>> 1);
int midVal = nums[mid];
if (midVal > first) low = mid;
else if (midVal < first) high = mid - 1;
else if (midVal == nums[high]) high--;//往左走一步,走边是较小的值
// 可合并。
else low = mid;
}
return binarySearch(nums, 0, low, target)
|| binarySearch(nums, low + 1, nums.length - 1, target);
}
// 二分查找target。
private boolean binarySearch(int[] nums, int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low >>> 1);
int midVal = nums[mid];
if (midVal == target) return true;
if (midVal < target) low = mid + 1;
else high = mid - 1;
}
return false;
}
public static void main(String[] args) {
new Search().search(new int[]{
2, 2, 2, 3, 2, 2, 2}, 2);
}
}
注:官方的答案,是一次抽象二分就搞定了,我这里写复杂了,纯当练习。
总结
1)抽象二分练习
参考文献
边栏推荐
- Analysis on the control condition and mode of go cooperation overtime exit
- 先序线索二叉树
- 聊聊swoole或者php cli 进程如何热重启
- Raspberry pie sends hotspot for remote login
- Uniapp - call payment function: Alipay
- php性能优化
- 6.常用指令(上)v-cloak,v-once,v-pre
- 达梦数据库修改字段信息采坑记
- Style setting when there is a separator in the qcombobox drop-down menu
- DPVS-FullNAT模式部署篇
猜你喜欢

森林的先序和中序遍历

7.常用指令(下)v-on,v-bind,v-model的常见操作

One article explains R & D efficiency! Your concerns are

SSL/TLS、对称加密和非对称加密和TLSv1.3

第五章 习题(124、678、15、19、22)【微机原理】【习题】

二叉排序树

Hibernate core api/ configuration file / L1 cache details

Bi-sql stored procedure (I)

实例:用C#.NET手把手教你做微信公众号开发(21)--使用微信支付线上收款:H5方式

权限设计=功能权限+数据权限
随机推荐
Download the latest V80 version of Google Chrome
MySQL version upgrade + data migration
Hibernate core api/ configuration file / L1 cache details
解析产品开发失败的5个根本原因
Use Baidu map API to set an overlay (infowindow) in the map to customize the window content
Tensorflow中CSV文件数据读取
Hibernate entity class curd, transaction operation summary
Online customer service - charging standards and service provision of third parties
final和static
Format the number. If the number is not enough, fill in 0, for example, 1:0001,25:0025
SSM整合学习笔记(主要是思路)
mysql
Qlabel text scrolling horizontally
期末复习【机器学习】
Uniapp -- framework arrangement and analysis summary
line-height小用
虚析构和纯虚析构及C ++实现
php中使用Makefile编译protobuf协议文件
MySQL自定义函数实例
Anaconda一文入门笔记