LeetCode(81) Search in Rotated Array II
2015-09-22 20:07
302 查看
题目
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.
分析
这是一道类似于LeetCode 33 的题目,不同的就是这道题有可能出现数字重复,所以,我们不可能像上题那样找到旋转点,然后两次二分查找;我们可以根据序列特点,以二分查找思想为基础,对该算法进行一定程序的改进。
AC代码
class Solution { public: bool search(vector<int>& nums, int target) { if (nums.empty()) return false; //求所给序列的长度 int len = nums.size(); int lhs = 0, rhs = len - 1; while (lhs <= rhs) { //右移一位减半,提升效能 int mid = (lhs + rhs) >> 1; if (target == nums[mid]) return true; //若左侧、中间、右侧值相等 则左右同时内移一位 if (nums[lhs] == nums[mid] && nums[mid] == nums[rhs]) { lhs++; rhs--; }//if else if (nums[lhs] <= nums[mid]) { if (nums[lhs] <= target && target < nums[mid]) { rhs = mid - 1; } else{ lhs = mid + 1; }//else }//elif else{ if (nums[mid] < target && target <= nums[rhs]) { lhs = mid + 1; }//if else{ rhs = mid - 1; }//else }//else }//while return false; } };
GitHub测试程序源码
相关文章推荐
- codeforces 578 B. Finding Team Member( Codeforces Round #320 (Div. 2) )
- LeetCode(81) Search in Rotated Array II
- ORA-12520与ORA-12514(监听相关问题)
- [MFC]CDocument文档类简介
- iOS开发 ----- APPDelegate回调
- iOS开发 ----- 网络请求
- Codeforces Round #104 (Div. 2) ABCD
- JAVA上机——
- 编译android内核和文件系统,已经安装jdk,提示build/core/config.mk:268: *** Error: could not find jdk tools.jar
- iOS开发 ---- 其他控件,弹窗,滑块,菊花,步进,分段等
- Codeforces 461B Appleman and Tree(木dp)
- JavaScript学习总结(一)基础部分
- C++多线程编程
- iOS开发 ----- UISearchBar_UISearchController
- 社团划分——Fast Unfolding算法
- Android开发之闹钟
- JAVA Current date and time
- NFS服务的简单使用
- hdu 5464 Clarke and problem(dp)
- SQL 语句的子查询例子