LeetCode Search in Rotated Sorted Array II

来源:互联网 发布:神仙水 去痘印 知乎 编辑:程序博客网 时间:2024/05/16 06:31

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.

旋转一次的有序数组含有重复的元素

遍历数组找到旋转的位置,左边、右边都是递增的

如果target在左边,在左侧二分搜索

否则在右侧二分搜索

public class Solution {    public boolean search(int[] A, int target) {        int middle = 0;int start = 0;int end = A.length;if(end==0)    return false;int i;for(i=1;i<end;i++){   //找到断点if(A[i]<A[i-1])break;}if(target>=A[0]&&target<=A[i-1]){start=0;end=i;}else{start=i;end=A.length;}while (true) {middle = (start + end) / 2;if (start >= end)return false;if (A[middle] == target)return true;if(A[middle] < target)start=middle+1;elseend=middle;}    }}


0 0