class Solution { public: int getLessIndex(vector<int> arr) { if (arr.empty()) return -1; //一定要有这句,否则出现段错误。。。。。。。 int len = arr.size(); if (len == 1 || arr[0]<arr[1]) return 0; if (arr[len - 1]<arr[len - 2]) return len - 1; int left = 1, right = len - 2; while (left <=right) { int mid = (left + right) / 2; if (arr[mid - 1]<arr[mid]) right = mid - 1; else if (arr[mid + 1]<arr[mid]) left = mid + 1; else return mid; } return left; } };
题目关键话:任意两个相邻的数不相等,那么保持条件arr[left] < arr[left - 1]arr[right] < arr[right + 1]则arr[left] 到 arr[right]之间一定有局部最小解
class Solution {
public:
int getLessIndex(vector<int> arr) {
if (arr.empty()){
return -1;
}
int len = arr.size();
if (len == 1 || arr[0] < arr[1]){ return 0;
}
if (arr[len - 1] < arr[len - 2]){
return len - 1;
}
int left = 1;
int right = len - 2;
while (left <= right){
int mid = (left + right) / 2;
if (arr[mid - 1] < arr[mid]){
right = mid - 1;
}
else if (arr[mid + 1] < arr[mid]){
left = mid + 1;
}
else{
return mid;
}
}
return 0;//随意返回,程序不会运行到这儿,不加这句,编译不过
}
};
classSolution {public:intgetLessIndex(vector<int> arr){intsize=arr.size();if(!size)return-1;if(size<2||arr[0]<arr[1])return0;if(arr.back()<arr[size-2])returnsize-1;for(inti=1;i<size-1;i++)if(arr[i]<arr[i-1]&&arr[i]<arr[i+1])returni;return0;}};
class Solution { public: // 此题的关键在于根据中间元素的大小对数组进行二分 // 解法的时间复杂度为 O(log n) int getLessIndex(vector<int> arr) { if ( arr.empty() ) return -1; // Size 为 1 直接 return, 不会执行第二个判断 else if ( arr.size() == 1 || arr[0] < arr[1] ) return 0; if ( arr[arr.size() - 1] < arr[arr.size() - 2] ) return arr.size() - 1; int left = 1; int right = arr.size() - 2; int mid = 0; while ( left < right ) { mid = ( left + right ) >> 1; if ( arr[mid] > arr[mid - 1] ) { right = mid - 1; } else if ( arr[mid] > arr[mid + 1] ) { left = mid + 1; } else { return mid; } } return left; } };
//这个题并不难,主要是要考虑到所有的临界情况 class Solution { public: int getLessIndex(vector<int> arr) { int n=arr.size(); if(n==0) return -1; if(n==1)return 0; if(arr[0]<arr[1])return 0; if(arr[n-1]<arr[n-2])return n-1; for(int i=1;i<n-1;i++){ if(arr[i]<arr[i-1]&&arr[i]<arr[i+1]) return i; } } };