描述

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;
}
}

最新文章

  1. JVM-String比较-字节码分析
  2. World Wind .NET源码编译问题处理
  3. 探讨js字符串数组拼接的性能问题
  4. 不让padding影响元素的宽度
  5. 【C++沉思录】句柄2
  6. LTIB常用命令1
  7. keil编译STM32工程时 #error directive: &quot;Please select first the target STM32F10x device used in your application (in stm32f10x.h file)&quot;
  8. phpcms(3) V9 常用函数 及 代码整理(转)
  9. Ext4 MVC CRUD操作
  10. C++数组与指针
  11. 解决浏览器兼容问题的css hack
  12. D3.js:动态效果
  13. 1_NAT模式和桥接模式下的网络配置
  14. php将字符串转为二进制数据串
  15. 响应式用法rem,需要加入这段JS
  16. 数据库SQLServr安装时出现--&quot;需要更新以前的Visual Studio 2010实例&quot;--状态失败
  17. thinkphp5---如何使用公共类
  18. (7)路由层的分发(不同app各自管理自己的和app的注册)
  19. 【转帖】 redis 命令 From https://www.cnblogs.com/zhouweidong/p/7550717.html
  20. 【监控】dubbo监控中心安装

热门文章

  1. spring cloud微服务实践四
  2. JVM GC 算法原理(转)
  3. go 函数定义
  4. SAS学习笔记23 线性回归、多元回归
  5. python实现数字0开始的索引,对应Execl的字母方法
  6. 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法
  7. MySQL的explain语句分析
  8. LeetCode 1103. Distribute Candies to People
  9. 在ASP.NET Core中实现自动注入、批量注入
  10. 八、wepy代码规范