[LeetCode] Search in Rotated Sorted Array II 解题报告
2016-01-12 11:08
471 查看
Follow up for “Search in Rotated Sorted Array”:
What if duplicates[/i] 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.
» Solve this problem
[解题思路]
确实有影响。比如,上一题(http://codingtmd.azurewebsites.net/leetcode-search-in-rotated-sorted-array-%e8%a7%a3%e9%a2%98%e6%8a%a5%e5%91%8a/)的程序中默认如果A[m]>=A[l],那么[l,m]为递增序列的假设就不能成立了,比如如下数据
[1,3,1,1,1]
所以,要是想增强该假设,有两个选择
1. 对于每一个递增序列,遍历之,确认。
2. 找到pivot点,然后确定对应序列搜索。
不写代码了。
Update: 3/18/2013. add the implementation
重新想了一下,其实不需要这么复杂。如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件
1. A[m]>A[l] 递增
2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。
实现如下
What if duplicates[/i] 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.
» Solve this problem
[解题思路]
确实有影响。比如,上一题(http://codingtmd.azurewebsites.net/leetcode-search-in-rotated-sorted-array-%e8%a7%a3%e9%a2%98%e6%8a%a5%e5%91%8a/)的程序中默认如果A[m]>=A[l],那么[l,m]为递增序列的假设就不能成立了,比如如下数据
[1,3,1,1,1]
所以,要是想增强该假设,有两个选择
1. 对于每一个递增序列,遍历之,确认。
2. 找到pivot点,然后确定对应序列搜索。
不写代码了。
Update: 3/18/2013. add the implementation
重新想了一下,其实不需要这么复杂。如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件
1. A[m]>A[l] 递增
2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。
实现如下
1: bool search(int A[], int n, int target) { 2: int start = 0; 3: int end = n-1; 4: while(start <= end) 5: { 6: int mid = (start+end)/2; 7: if(A[mid] == target) return true; 8: if(A[start] < A[mid]) 9: { 10: if(target>=A[start] && target<A[mid]) 11: end = mid-1; 12: else 13: start = mid+1; 14: } 15: else if(A[start] > A[mid]) 16: { 17: if(target>A[mid] && target<=A[end]) 18: start = mid+1; 19: else 20: end = mid-1; 21: } 22:
else //skip duplicate one, A[start] == A[mid] 23: start++;
24: } 25: return false; 26: }
相关文章推荐
- [LeetCode] Search Insert Position 解题报告
- [LeetCode] Set Matrix Zeroes 解题报告
- [LeetCode] Simplify Path 解题报告
- [LeetCode] Sort Colors 解题报告
- [LeetCode] Spiral Matrix 解题报告
- [LeetCode] Sqrt(x) 解题报告
- [LeetCode] String to Integer (atoi) 解题报告
- [LeetCode] Subsets 解题报告
- [LeetCode] Subsets II 解题报告
- [LeetCode] Substring with Concatenation of All Words 解题报告
- [LeetCode] Swap Nodes in Pairs 解题报告
- [LeetCode] Symmetric Tree 解题报告
- Csharp 简单操作Word模板文件
- gleez 下分页功能优化
- 常用的sql语句(转)
- UINavigationController 与 UITabBarController
- ThinkPHP3.2 分页实现
- Android 之 Fresco 显示圆形图片 之坑
- du&df
- pip常用操作