LeetCode 81. Search in Rotated Sorted Array II(搜索旋转的数组)
2016-05-22 05:30
756 查看
原题网址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
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.
方法:二分法查找,注意当头尾相等时,前后两段都需要查找。
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.
方法:二分法查找,注意当头尾相等时,前后两段都需要查找。
public class Solution { private boolean search(int[] nums, int target, int from, int to) { if (from > to) return false; if (from == to) return nums[from] == target; int m = (from+to)/2; if (nums[m] == target) return true; if (nums[from] == nums[to]) return search(nums, target, from, m-1) || search(nums, target, m+1, to); if (nums[from] < nums[to]) { if (nums[m] < target) return search(nums, target, m+1, to); else return search(nums, target, from, m-1); } // nums[from] > nums[to] if (nums[from] <= nums[m]) { if (nums[from] <= target && target < nums[m]) return search(nums, target, from, m-1); return search(nums, target, m+1, to); } else { if (nums[m] < target && target <= nums[to]) return search(nums, target, m+1, to); return search(nums, target, from, m-1); } //此处错误!!! // if ((nums[from] <= target && target < nums[m]) || (target < nums[m] && nums[m] <= nums[to])) return search(nums, target, from, m-1); // return search(nums, target, m+1, to); } public boolean search(int[] nums, int target) { return search(nums, target, 0, nums.length-1); } }
相关文章推荐
- LeetCode 80. Remove Duplicates from Sorted Array II(删除重复)
- Python64位安装模块问题
- LeetCode 79. Word Search(单词查找)
- LeetCode 77. Combinations(组合)
- LeetCode 78. Subsets(子集)
- LeetCode 74. Search a 2D Matrix(搜索矩阵)
- LeetCode 75. Sort Colors(颜色排序)
- LeetCode 76. Minimum Window Substring(最小窗口子串)
- LeetCode 72. Edit Distance(编辑距离)
- LeetCode 73. Set Matrix Zeroes(矩阵清零)
- 输入输出外挂总结
- leetcode #22 in cpp
- 关于Gson.jar导入正常使用,代码无错,但程序执行解析时崩溃的一些问题
- [PWA] 18. Clean the photo cache
- leetcode #21 in cpp
- mathematica试除法解素数问题
- 全局eval的实现
- 法国劳动法案引大罢工 一场“无解”的左翼运动
- [PWA] 17. Cache the photo
- Notepad++正则表达式中几点需要注意的地方