首页 > 代码库 > Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

 

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.

这道题说如果有重复的元素会不会对,时间之类的有影响,对于我这种懒人直接copy上一题的过去A了,不过感觉和线性搜索O(n)的时间复杂度提升不是太多,只是后面的用了二分查找O(logn)

虽然是一样的,还是贴一下代码,恩,我就是这么无聊

 1 public class Solution { 2     public boolean search(int[] A, int target) { 3         int i = 0; 4         for(; i < A.length; i++){ 5             if(i > 0 && A[i - 1] > A[i])            //找出轴的位置 6                 break; 7             if(A[i] == target) 8                 return true; 9         }10         if(i == A.length)                            //没有找到11             return false;12         //从轴的位置到最后开始二分查找从i的位置开始到length - 113         int low = i;14         int high = A.length - 1;15         int middle;16         while(low <= high){17             middle = (low + high) / 2;18             if(A[middle] == target)19                 return true;20             else if(A[middle] > target){        //前半段找21                 high = middle - 1;22             }else{                                //后半段找23                 low = middle + 1;24             }25         }26         27         return  false;28     }29 }

 

Search in Rotated Sorted Array II