[LeetCode]Search in Rotated Sorted Array II

Search in Rotated Sorted Array II

My Submissions
Question
Total Accepted: 50992  Total Submissions: 162671  Difficulty: Medium

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.

Subscribe to see which companies asked this question













这个题目我想了好久才过的,本身循环排序数据就不是很好做。这个由于有重复数,所以当重复数是最前面和最后面的时候需要进行递归。

public class Solution {
    public boolean search(int[] nums, int target) {
		return search(nums, target, 0, nums.length-1);
	}
	public boolean search(int[] nums, int target,int m,int n) {
		 if(m>n)return false;
		 if(m<0||n>=nums.length)return false;
		 int i=m;int j=n;
		 if(nums[m]==target)return true;
         while(i<=j){
        	 int mid = (i+j)/2;
        	 if(nums[mid]==target){
        		 return true;
        	 }
        	 else{
        		 if(nums[mid]<target){
        			 if(nums[mid]>nums[m]){
        				 i=mid+1;
        			 }
        			 else{
        				 if(nums[mid]<nums[m]){
        					 if(target<nums[m]){
        						 i=mid+1;
        					 }
        					 else{
        						j=mid-1;
        					 }
        				 }
        				 else{
        					 if(search(nums, target, m+1, mid-1)||search(nums, target, mid+1, n)){
        						 return true;
        					 }
        					 else{
        						 return false;
        					 }
        				 }
        			 }
        		 }
        		 else{
        			 if(nums[mid]<nums[m]){
        				 j=mid-1;
        			 }
        			 else{
        				 if(nums[mid]>nums[m]){
        					 if(target>nums[m]){
        						 j=mid-1;
        					 }
        					 else{
        						 i=mid+1;
        					 }
        				 }
        				 else{
        					 if(search(nums, target, m+1, mid-1)||search(nums, target, mid+1, n)){
        						 return true;
        					 }
        					 else{
        						 return false;
        					 }
        				 }
        			 }
        		 }
        	 }
         }
         return false;
    }
}


你可能感兴趣的:([LeetCode]Search in Rotated Sorted Array II)