leetcode 081 —— Search in Rotated Sorted Array II

来源:互联网 发布:飞秋for mac 下载 编辑:程序博客网 时间:2024/05/20 19:49

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.


思路;循环数组的查找,之前的题,数组里的元素是单独的,这个是可以重复出现,还是用二分法。

class Solution {public:bool search(vector<int>& nums, int target) {int l = 0, r = nums.size() - 1;while (l <= r){int m = (l + r) / 2;if (nums[m] == target||nums[l]==target||nums[r]==target) return true;else if (nums[m] > nums[l]){   //左边为已排序数组if (nums[l] < target&&nums[m] > target)r = m - 1;elsel = m + 1;}else if (nums[m] < nums[r]){    //右边为已排序数组if (nums[m] < target&&nums[r] > target)l = m + 1;elser = m - 1;}elsel++; //这是本题最精华的地方所在,当两边等于中间,从左往右搜索}return false;}};



0 0
原创粉丝点击