1. 程式人生 > >旋轉陣列找最小值

旋轉陣列找最小值

注意問題

一定要考慮到非遞減包括兩種情況,遞增和不變。所以針對不變的情形要設定相應的處理方法。

程式碼

class Solution {
public:
	int minNumberInRotateArray(vector<int> rotateArray) {
		if (rotateArray.size() == 0) return 0;
		int left = 0, right = rotateArray.size() - 1, middle=0;

		while (rotateArray[left]>=rotateArray[right]){
			if (right == left + 1){
				middle = right;
				break;
			}
			middle = (left + right) / 2;
			if (rotateArray[left] == rotateArray[middle] && rotateArray[middle] == rotateArray[right]){
				int result = rotateArray[left];
				for (int i = left+1; i <= right; i++){
					if (rotateArray[i] < result){
						result = rotateArray[i];
					}
				}
			}
			
			if (rotateArray[middle] >= rotateArray[left]){
				left = middle;
			}
			else{
				right = middle;
			}
		}

		return rotateArray[middle];
	}
};