[LeetCode]26. Search in Rotated Array II旋转数组查找II
2015-10-15 15:51
447 查看
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.
解法:同旋转数组查找I,本题也使用二分查找,只是在nums[mid]和nums[right](或者nums[right])比较时若二者相等则left++(或者right--)即可。nums[mid]与nums[left]比较的代码:
nums[mid]与nums[right]比较的代码:
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.
解法:同旋转数组查找I,本题也使用二分查找,只是在nums[mid]和nums[right](或者nums[right])比较时若二者相等则left++(或者right--)即可。nums[mid]与nums[left]比较的代码:
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); bool res = false; int left = 0, right = n - 1; while(left <= right) { int mid = ((left + right) >> 1); if(target == nums[mid]) { res = true; break; } else if(nums[mid] > nums[left]) //前半部分有序 { if(target >= nums[left] && target < nums[mid]) right = mid - 1; else left = mid + 1; } else if(nums[mid] < nums[left]) //后半部分有序 { if(target > nums[mid] && target <= nums[right]) left = mid + 1; else right = mid - 1; } else //nums[mid]==nums[left]的情况,包括mid=left和存在重复值两种情况 left++; } return res; } };
nums[mid]与nums[right]比较的代码:
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); bool res = false; int left = 0, right = n - 1; while(left <= right) { int mid = (left + right) >> 1; if(target == nums[mid]) { res = true; break; } else if(nums[mid] < nums[right]) //后半部分有序 { if(target > nums[mid] && target <= nums[right]) left = mid + 1; else right = mid - 1; } else if(nums[mid] > nums[right]) //前半部分有序 { if(target >= nums[left] && target < nums[mid]) right = mid - 1; else left = mid + 1; } else //存在重复值的情况 right--; } return res; } };
相关文章推荐
- linux安装svn客户端subversion及使用方法
- 【基础练习】【搜索】codevs1008 选数题解
- Jquery MVC 解决跨域问题
- Android 23 Connot resolve method updateNotification.setLatestEventInfo()解决方案
- 3-排序-快速排序
- 参数为函数指针
- Android:根据上下文Context获取Activity
- 使用LinkedHashMap构建LRU的Cache
- Python 基础语法(一)
- linux批量重命名
- Golang闭包
- 程序员重装系统后,要安装的工具
- 设置hidesBottomBarWhenPushed无效果
- AndroidSQLite建表语句
- SQL SERVER – Repair a SQL Server Database Using a Transaction Log Explorer
- 一位年薪百万老员工的离职忠告
- 欢迎使用CSDN-markdown编辑器
- 多线程的那点儿事(之避免死锁)
- 抽象类和接口的区别
- 计算机网络七层协议模型