leetcode -- Search in Rotated Sorted Array II
2013-08-01 20:38
316 查看
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.
上题中A[l] <= A[m]在数组中有重复元素时无法保证[l,m]是sorted
当输入:[1,3,1,1,1], 3
这里参考:
分为两种情形:http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array_3.html
1. A[l] < A[m] 则[l, m]是递增的
2. A[l] = A[m] 此时是重复元素,无法确认哪一部分是有序的,则跳过l,l++
ref:
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.
上题中A[l] <= A[m]在数组中有重复元素时无法保证[l,m]是sorted
当输入:[1,3,1,1,1], 3
这里参考:
分为两种情形:http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array_3.html
1. A[l] < A[m] 则[l, m]是递增的
2. A[l] = A[m] 此时是重复元素,无法确认哪一部分是有序的,则跳过l,l++
public class Solution { public boolean search(int[] A, int target) { // Start typing your Java solution below // DO NOT write main() function int len = A.length; // binary search int l = 0; int r = len - 1; while(l <= r){ int m = (l + r) / 2; if(target == A[m]) return true; // lower is sorted if(A[l] < A[m]){ if(A[l] <= target && target < A[m]) r = m - 1; else{ l = m + 1; } } else if(A[l] > A[m]) { // upper is sorted if(A[m] < target && target <= A[r]){ l = m + 1; } else{ r = m - 1; } } else { l = l + 1; } } return false; } }
ref:
二分搜索及其扩展
http://www.pcw8510.com/?p=3294相关文章推荐
- LeetCode | Search in Rotated Sorted Array II
- 个人记录-LeetCode 81. Search in Rotated Sorted Array II
- Search in Rotated Sorted Array II -- LeetCode
- leetcode - 81.Search in Rotated Sorted Array II
- LeetCode: Search in Rotated Sorted Array II
- [leetcode] 81. Search in Rotated Sorted Array II
- [LeetCode] 098: Search in Rotated Sorted Array II
- [leetcode] Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array I&II
- Leetcode 81. Search in Rotated Sorted Array II (Medium) (java)
- [leetcode] Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- LeetCode--Search in Rotated Sorted Array II
- LeetCode之Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- Leetcode 81. Search in Rotated Sorted Array II
- [leetcode-81]Search in Rotated Sorted Array II(C)
- leetcode 81: Search in Rotated Sorted Array II
- LeetCode Search in Rotated Sorted Array II
- [LeetCode]Search in Rotated Sorted Array II@python