leetcode解题报告(4):Search in Rotated Sorted ArrayII
2024-09-05 03:19:26
描述
Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
分析
如果允许重复,那么上一题中“若A[first] <= A[mid],则[first,mid]区间有序”的假设就不成立了,比如可能存在旋转后形如[1,3,1,1,1]的数组。
显然,如果A[first]<=A[mid]不能确定是否有序,就把这个条件细分一下:
- 若A[first] < A[mid],就一定递增;
- 若A[first] == A[mid],则确定不了,就将first加1,往下看一步即可。
代码如下:
class Solution{
public:
int search(int A[],int n,int target){
int first = 0,last = n;
const int mid = (first + mid) / 2; //note that mid is const,which means that we would not modify the value of mid before a new loop starts
while(first != mid){
if(A[mid] == target)
return mid;
if(A[first] < A[mid]){
if(A[first] <= target && target < A[mid])
last = mid;
else
first = mid + 1;
}
else if(A[mid] == A[first])
++first; //skip duplicatted one
else{
if(A[mid] <= target && target <= A[last - 1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
}
最新文章
- JVM-String比较-字节码分析
- World Wind .NET源码编译问题处理
- 探讨js字符串数组拼接的性能问题
- 不让padding影响元素的宽度
- 【C++沉思录】句柄2
- LTIB常用命令1
- keil编译STM32工程时 #error directive: ";Please select first the target STM32F10x device used in your application (in stm32f10x.h file)";
- phpcms(3) V9 常用函数 及 代码整理(转)
- Ext4 MVC CRUD操作
- C++数组与指针
- 解决浏览器兼容问题的css hack
- D3.js:动态效果
- 1_NAT模式和桥接模式下的网络配置
- php将字符串转为二进制数据串
- 响应式用法rem,需要加入这段JS
- 数据库SQLServr安装时出现--";需要更新以前的Visual Studio 2010实例";--状态失败
- thinkphp5---如何使用公共类
- (7)路由层的分发(不同app各自管理自己的和app的注册)
- 【转帖】 redis 命令 From https://www.cnblogs.com/zhouweidong/p/7550717.html
- 【监控】dubbo监控中心安装