153尋找旋轉排序數組中的最小值(折半查找)

1、題目描述

假設按照升序排序的數組在預先未知的某個點上進行了旋轉。

( 例如,數組 [0,1,2,4,5,6,7] 可能變爲 [4,5,6,7,0,1,2] )。

請找出其中最小的元素。

你可以假設數組中不存在重複元素。

2、示例

輸入: [3,4,5,1,2]
輸出: 1

3、題解

基本思想:折半查找

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
	int findMin(vector<int>& nums) {
		//基本思想:折半查找
		int low = 0, high = nums.size() - 1;
		while (low < high)
		{
			int mid = (low + high) / 2;
			if (nums[mid] < nums[high])
			{
				high = mid;
			}
			else if (nums[mid] > nums[high])
			{
				low = mid + 1;
			}
		}
		return nums[low];
	}
};
int main()
{
	Solution solute;
	vector<int> nums = { 1,2,3 };
	cout << solute.findMin(nums) << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章