题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
'''
minnumber = rotateArray[0]
for i in range(len(rotateArray)):
if rotateArray[i] < minnumber:
minnumber = rotateArray[i]
return minnumber
'''
if len(rotateArray) == 0:
return 0
low = 0
high = len(rotateArray) - 1
while high - low > 1:
middle = (low + high) // 2
if rotateArray[middle] == rotateArray[low] and rotateArray[low] == rotateArray[high]:
for i in range(low+1,high+1):
if rotateArray[i] < rotateArray[low]:
return rotateArray[i]
elif rotateArray[middle] >= rotateArray[low]:
low = middle
elif rotateArray[middle] <= rotateArray[high]:
high = middle
return rotateArray[high]
Lintcode
585.Maximum Number in Mountain Sequence
Description
Given a mountain sequence of n integers which increase firstly and then decrease, find the mountain top.
Example 1:
Input: nums = [1, 2, 4, 8, 6, 3]
Output: 8
Example 2:
Input: nums = [10, 9, 8, 7],
Output: 10
class Solution {
public:
/**
* @param nums: a mountain sequence which increase firstly and then decrease
* @return: then mountain top
*/
int mountainSequence(vector<int> &nums) {
// write your code here
int start = 0,end = nums.size();
while(start+1 < end){
int left = start + (end - start) / 2;
int right = end - (end - left) / 2;
if(nums[left] < nums[right]){
start = left + 1;
}
else if(nums[left] > nums[right]){
end = right -1;
}
else {
start = left;
end = right;
}
}
return max(nums[start],nums[end]);
}
};
网友评论