本文主要是介绍LeetCode第33题之 Search in Rotated Sorted Array,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C++代码:
#include <iostream>
#include <vector>
using namespace std;class Solution {
public:int search(vector<int>& nums, int target) {int sz = nums.size();int l = 0;int r = sz-1;int mid;while (l<=r){mid = (l+r)/2;if (nums[mid] == target)return mid;//左半部分有序else if (nums[mid] >= nums[l]){//如果target在左半部分if (nums[l] <= target && nums[mid] > target)r = mid-1;//如果在不在左半部分elsel = mid + 1;}//此时(nums[mid] < nums[l]),右半部分有序else{//如果在右半部分if (nums[mid] < target && nums[r] >= target)l = mid+1;//如果不在右半部分elser = mid - 1;} }return -1;}
};int main()
{Solution s;vector<int> v;/*v.push_back(3);v.push_back(4);v.push_back(5);v.push_back(6);v.push_back(7);v.push_back(8);v.push_back(9);v.push_back(0);v.push_back(1);v.push_back(2);*/v.push_back(3);v.push_back(1);cout<<s.search(v, 1)<<endl;return 0;
}
这篇关于LeetCode第33题之 Search in Rotated Sorted Array的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!