Leetcode#154Find Minimum in Rotated Sorted Array II

Find Minimum in Rotated Sorted Array II

 Total Accepted: 25678 Total Submissions: 80978My Submissions

Question Solution 


Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

The array may contain duplicates.


Show Tags

分析:如果沒有重複的可以直接比較就可以中間項和末尾項即可區別出使用哪一個片段,此題說明是重複項存在,因此除非極端情況下可,二分取其一處理外,其他情況兩部分都要處理


例如,一種情況

3 3 3 3 3 1 3


public class Solution {

    int fm(int[] nums, int start, int end){

        int l=end-start+1;

        if(l==1)

            return nums[start];

        else {

            int s=start;

            int e=end;

            int m=(s+e)/2;

            int min=0;

            if(nums[m]<nums[e])

                min=fm(nums, s, m);

            else

            {

                int m1=fm(nums, s, m);

                min=fm(nums, m+1, e);

                if(m1<min)

                    min=m1;

            }

            return min;

        }    

    }

    

    public int findMin(int[] nums) {

        int x=fm(nums,0,nums.length-1);

        return x;

    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章