Search in Rotated Sorted Array II--LeetCode
来源:互联网 发布:美团数据分析工资 编辑:程序博客网 时间:2024/06/02 02:55
1.题目
Search in Rotated Sorted Array II
Follow up for “Search in Rotated Sorted Array”:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?Suppose an array sorted in ascending order 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).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
2.题意
将升序数组旋转,找出target所在的下标,数组中可能有重复值
3.分析
类似Search in Rotated Sorted Array
允许重复值,可能出现两种情况
如[3 1 1] 和 [1 1 3 1],
当中间值等于最右值时,无法确定目标值3的所在范围
对于这种情况,只要把最右值左移并继续循环,一直移到不同值即可
这一步使得算法的复杂度由原先的O(logn)变成了O(n)
4.代码
class Solution {public: bool search(vector<int>& nums, int target) { if(nums.size() == 0) return false; int left = 0; int right = nums.size() - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) return true; if(nums[mid] < nums[right]) { if(nums[mid] < target && target <= nums[right]) left = mid + 1; else right = mid - 1; } else if(nums[mid] > nums[right]) { if(nums[left] <= target && target < nums[mid]) right = mid - 1; else left = mid + 1; } else --right; } return false; }};
阅读全文
0 0
- LeetCode: Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- LeetCode : Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- [Leetcode] Search in Rotated Sorted Array II
- [leetcode] Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array II
- [leetcode] Search in Rotated Sorted Array II
- LeetCode-Search in Rotated Sorted Array II
- LeetCode - Search in Rotated Sorted Array II
- 【Leetcode】Search in Rotated Sorted Array II
- Leetcode: Search in Rotated Sorted Array II
- 【leetcode】Search in Rotated Sorted Array II
- leetcode Search in Rotated Sorted Array II
- Leetcode: Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- LeetCode | Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- 枚举实例
- ubuntu18安装freeswitch1.8
- Spring系列之beanFactory与ApplicationContext
- Java知识点总结(三)JavaFX
- nyoj 228士兵杀敌(五)
- Search in Rotated Sorted Array II--LeetCode
- 浅谈JavaScript new对象的四个过程
- or,and,group by,having
- 奇异值分解(SVD)原理详解及推导
- 集合工具类
- 18、进程间通信IPC(1)
- [微机原理]补码运算原理
- centos7安装shipyard没有本地容器及镜像
- 转载致谢声明