leetcode 33:Revised Binary Search
来源:互联网 发布:哪家的4g网络好 编辑:程序博客网 时间:2024/05/21 06:43
题目:
Suppose a sorted array 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
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
class Solution {public: int search(vector<int>& nums, int target) { }};思路:
虽然不是所有元素都排序了的,但至少可以分成两部分,且两部分都是排好序的。因此我们还是可以用binary search方法来解。
但是怎样来进行取舍呢,即不能简单的根据target与中间元素的大小来决定是搜索左半边还是右半边。
注意到,不管上面的怎样旋转,我们取定中间元素后,一定有半边是严格排序的,比如:
6 7 0 1 2 4 5,我们取中间元素1,则右边是严格排序的,同样地
2 4 5 6 7 0 1,我们取中间元素6,则左边是严格排序的。
所以只需判断target是否在严格排序那边即可。
代码看起来比较复杂,其实很好理解,时间复杂度:O(lgn)
class Solution {public:int search(vector<int>& nums, int target) {int size = nums.size();if (size == 0) return -1;int low = 0, high = nums.size() - 1;return notBinary(nums, low, high, target);}int binary(vector<int>&nums, int low, int high,int target){if (low == high && nums[low] == target) return low;else if (low == high) return -1;int mid = (low + high) / 2;if (nums[mid] == target) return mid;else if (nums[mid] > target&&mid>low) return binary(nums,low,mid-1,target);else if(mid<high) return binary(nums,mid+1,high,target);}int notBinary(vector<int>&nums, int low, int high, int target){if (low == (high - 1)) return nums[low] == target ? low : (nums[high] == target ? high : -1);if (low == high && nums[low] == target) return low;else if (low == high) return -1;int mid = (low + high) / 2;if (nums[mid] == target) return mid;if (target >= nums[low] && target < nums[mid] &&mid>low) return binary(nums, low, mid - 1, target);else if (target>nums[mid] && target <= nums[high] &&mid<high) return binary(nums, mid+1, high, target);else if (nums[low] < nums[mid] &&mid<high) return notBinary(nums, mid + 1, high, target);else if(mid>low) return notBinary(nums, low , mid-1, target);else return -1;}};
0 0
- leetcode 33:Revised Binary Search
- [Leetcode]Binary Search Tree
- leetcode Binary Search
- LeetCode Binary Search
- leetcode -- Binary search (5)
- leetcode -- Binary search (6)
- LeetCode--Binary Search
- LeetCode 33, Search in Rotated Sorted Array-----Binary Search
- LeetCode - Array/Binary Search - Search Insert Position
- LeetCode: Unique Binary Search Trees
- LeetCode: Validate Binary Search Tree
- LeetCode: Recover Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode: Recover Binary Search Tree
- LeetCode : Unique Binary Search Trees
- LeetCode : Validate Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [Leetcode] Unique Binary Search Trees
- 51nod 1136 欧拉函数
- Linux 浏览器下安装 Flash
- 《项目管理艺术》第五、六章读书摘要-想法从何而来、有了想法该如何去做
- There is no Action mapped for namespace [/] and action name [spropertyvalue] associated with context
- 面试技巧及注意事项
- leetcode 33:Revised Binary Search
- 使用注解提供view引用和点击事件
- Android的Adapter用法理解
- javascript 实现输入框只能输入数字
- 使用DBUtils编写通用的DAO
- 序列模式挖掘算法BIDE
- 抽象类与接口的区别与使用
- WF对象引用1
- Mac上无法安装jekyll