标签:show com style http solution vector targe alt 思路
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
代码:
#include <algorithm> class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); if(n == 0) return -1; if(n == 1) return (nums[0]==target) ? 0 : -1; int l = 0; int h = n-1; while(l <= h) { int mid = (l+h) >> 1; if(nums[mid] == target) return mid; if(nums[0] <= nums[mid]) { if(nums[0] <= target && target < nums[mid]) { h = mid-1; } else { l = mid+1; } } else { if(nums[mid] < target && target <= nums[n-1]) { l = mid+1; } else { h = mid-1; } } } return -1; } };
思路:二分的本质是能够排除一半的元素所以能够加快速度,所以仔细思考能否舍弃不可能解。
标签:show com style http solution vector targe alt 思路
原文地址:https://www.cnblogs.com/FriskyPuppy/p/12940471.html