Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
本题利用二分算法的思想,判断target是在前半段还是后半段,再分开查找。时间:7ms。代码如下:
class Solution { public: int search(vector<int>& nums, int f, int l, int target) { if (f>l) return -1; if (target == nums[f]) return f; if (target == nums[l]) return l; int mid = f + (l - f) / 2; if (target == nums[mid]) return mid; if (nums[f] == nums[l] && nums[f] == nums[mid]){ for (int i = f; i<l; i++){ if (nums[i] == target) return i; } return -1; } if (nums[f] < target){ if (nums[f]<nums[mid]&&target>nums[mid]) return search(nums, mid + 1, l, target); else return search(nums, f, mid - 1, target); } else if(nums[l]>target){ if (nums[mid]<nums[l] && target < nums[mid]) return search(nums, f, mid - 1, target); else return search(nums, mid + 1, l, target); } return -1; } int search(vector<int>& nums, int target) { if (nums.size() == 0) return -1; return search(nums, 0, nums.size()-1, target); } };
时间: 2024-09-01 14:40:05