您的位置:首页 > 其它

LeetCode - Find Minimum in Rotated Sorted Array II

2015-01-23 12:13 316 查看
Find Minimum in Rotated Sorted Array II

2015.1.23 11:41

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.

Solution:

  With duplicates in the array, it would be a little harder to perform binary search.

  Consider the ocassion "1 ... 1 ... 1", with the left, right and middle elements being all "1", you don't know if the rotated pivot will lie in the left or right half of the sequence. If we scan the sequence at one end, removing all duplicates that are equal to the other end, it will make a legal sequence for binary search.

  Here're some example data for my idea:

    {1, 1, -1, 0, 1, 1, 1} -> remove {1, 1} on the right -> {1, 1, -1, 0}

    {1, 1, 1, 2, 3} -> remove nothing -> {1, 1, 1, 2, 3}

    {1, 1, 1, 1, 1} -> all equal to the left end are removed -> {1}

  The next step would be a binary search, similar to the upper_bound() function in <algorithm>.

  Total time complexity is on average O(log(n)), but O(n) in worst cases. Space complexity is O(1).

Accepted code:

class Solution {
public:
int findMin(vector<int> &num) {
int n = (int)num.size();

while (n > 1 && num[0] == num[n - 1]) {
--n;
}

if (n == 1 || num[0] < num[n - 1]) {
return num[0];
}

int ll, mm, rr;

ll = 0;
rr = n - 1;
while (rr - ll > 1) {
mm = ll + (rr - ll) / 2;
if (num[mm] >= num[ll]) {
ll = mm;
} else {
rr = mm;
}
}

return num[rr];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: