LeetCode 81. Search in Rotated Sorted Array II
2016-04-24 10:53
435 查看
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.
Worst Time Complexity would be O(N).... for example: whole array is [4, 4, 4, 4, 4.....4] then the target is 3.
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.
Worst Time Complexity would be O(N).... for example: whole array is [4, 4, 4, 4, 4.....4] then the target is 3.
#include <vector> #include <iostream> using namespace std; bool search(vector<int>& nums, int target) { if(nums.size() == 0) return false; int low = 0; int high = nums.size() - 1; while(low <= high) { int mid = low + (high - low) / 2; if(nums[mid] == target) return true; if(nums[mid] < nums[high]) { if(target <= nums[high] && target > nums[mid]) { low = mid + 1; } else high = mid - 1; } else if(nums[mid] > nums[high]) { if(target >= nums[low] && target < nums[mid]) { high = mid - 1; } else { low = mid + 1; } } else { high--;} } return false; } // duplicates in rotated sorted array. // For example: 4, 4, 5, 6, 1, 2, 3, 4, target is 3. int main(void) { vector<int> nums{4, 4, 5, 6, 1, 2, 3, 4}; int target = 2; bool found = search(nums, target); cout << found << endl; }
相关文章推荐
- 关于 JavaScript中的 Object.create()
- LeetCode——049
- 如何在单元测试中测试异步函数,block回调这种
- 使用Nginx配置资源虚拟路径
- 如何用U盘装centos
- QML Applications
- 希尔排序 时间复杂度 证明
- Objective-C 内存管理
- 如何支持多种设备-语言篇
- SQL第一节课
- Java中处理异常中return关键字
- mysqlbinlog的使用
- 栈的应用实践——括号匹配的检验
- Ecshop PC 商品列表页面下拉加载商品
- 对象的引用及传递
- 启动图片
- QML视图元素  Visual Elements In QML Qt 5.6.0 Reference Documentation
- Java枚举
- Matlab SVM
- 第八周进度条