【原创】leetCodeOj --- Find Minimum in Rotated Sorted Array II 解题报告

题目地址:

https://oj.leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/

 

题目内容:

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.

 

方法:

此题难点在于元素可重复,因此,关键在于如何分解出子问题。大概思路如下:

设首节点为C,中结点为A,末尾结点为D,则有:


C  <  D ? 返回 C


C == D ? 找到下一个为C不等的F,递归调用F,D。若不存在F,则返回C


C  >  D ? C  <  A ? ---> 递归调用A+1,D
              C  >  A ? ---> 寻找A之前第一个和A不等的值B,若B > A则返回A,若B < A则递归调用C,B
              C == A ? ---> 递归调用A+1,D

 

全部代码:

class Solution {
public:
    int findMin(vector<int> &num) {
        int len = num.size();
        return trueStuff(num,0,len - 1);
    }
    
    int trueStuff(vector<int> &num,int start,int fin)
    {
        if (start == fin)
            return num[start];
        if (num[start] < num[fin])
            return num[start];
        if (num[start] == num[fin])
        {
            while (start < fin)
            {
                if (num[start] != num[fin])
                    break;
                start ++;
            }
            if (start == fin)
                return num[start];
            else
                return trueStuff(num,start,fin);
        }
        int mid = (start + fin) / 2;
        if (num[start] < num[mid])
            return trueStuff(num,mid + 1,fin);
        if (num[start] > num[mid])
        {
            int tmp = mid;
            while (num[tmp] == num[tmp-1])
                tmp --;
            tmp --;
            if (num[tmp] > num[mid])
                return num[mid];
            else
                return trueStuff(num,start,tmp);
        }
        if (num[start] == num[mid])
            return trueStuff(num,mid + 1,fin);
    }
};

 

posted on 2014-10-22 14:14  shadowmydx'sLab  阅读(206)  评论(0编辑  收藏  举报

导航