博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode#81]Search in Rotated Sorted Array II
阅读量:4326 次
发布时间:2019-06-06

本文共 2182 字,大约阅读时间需要 7 分钟。

The problem:

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.

 

My analysis:

It metrics if we really master the idea underlying binary search.

What the duplicates bring into this problem is that:
For checking condition: if (A[low] <= A[mid])
What if low and mid not equal to 0, but A[low] and A[mid] have the same value ?
In this situation, we no longer be able to decide to iterate on which partion any more. We can only gain the information of ordered paration from the comparsion from A[low] and A[mid].
How to solve this problem?
? 1. directly move the ptr of mid, mid ++ or mid --. meaningless!!!
cause:
while (low <= high) {
mid = (low + high) / 2;
? 2. move the ptr of high, high--. wrong!!!
cause:
we write our checking condition based on A[low], we only knwo A[low] == A[mid] at present.

3. move the ptr of low. absoultely right!!! This could lead following effects:

a. move low ptr, reducing the range need to search. (since the current is not the target, we could discard it!)
b. move mid ptr. mid = (low + high) / 2. It make sense too, since A[mid] != target, we could discard it.

My solution:

public class Solution {    public int search(int[] A, int target) {                if (A.length == 0)            return -1;                int low = 0;        int high = A.length - 1;        int mid = -1;                while (low <= high) {            mid = (low + high) / 2;                        if (A[mid] == target)                return mid;                        if (A[low] <= A[mid]) { //either left partion or right partion is perfectly sorted.                                if (A[low] <= target && target < A[mid])                    high = mid - 1;                else                     low = mid + 1;                                } else{                                if (A[mid] < target && target <= A[high])                    low = mid + 1;                else                     high = mid - 1;            }        }                return -1;    }}

 

转载于:https://www.cnblogs.com/airwindow/p/4205201.html

你可能感兴趣的文章
Detours信息泄漏漏洞
查看>>
win32使用拖放文件
查看>>
Android 动态显示和隐藏软键盘
查看>>
raid5什么意思?怎样做raid5?raid5 几块硬盘?
查看>>
【转】how can i build fast
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
图论知识,博客
查看>>
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>