标签:style blog http color os art
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.
https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
思路:类似Search in Rotated Sorted Array的思路,只不过现在的问题是有重复,可能出现a[l]==a[m]的极端情况,无法判断哪半边有序,因此这种情况下只能一步一步移动l 直到不相等然后通过二分判断。
复杂度:极端情况每次都是减一 而不是减去一半,所以复杂度是O(N)。
/** * http://blog.csdn.net/linhuanmars/article/details/20525681 * * @author jd * */ public class Solution { public boolean search(int[] A, int target) { if (A == null || A.length == 0) return false; int l = 0; int r = A.length - 1; while (l <= r) { int m = (l + r) / 2; if (A[m] == target) return true; if (A[m] > A[l]) { if (A[m] > target && A[l] <= target) { r = m - 1; } else { l = m + 1; } } else if (A[m] < A[l]) { if (A[m] < target && A[r] >= target) { l = m + 1; } else { r = m - 1; } } else { l++; } } return false; } public static void main(String[] args) { System.out.println(new Solution().search(new int[] { 3, 1, 1 }, 3)); System.out.println(new Solution().search(new int[] { 2, 3, 3, 3, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 2, 3, 3, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 3, 3, 2, 3 }, 2)); System.out.println(new Solution().search(new int[] { 3, 3, 3, 3, 2 }, 2)); } }
参考:
http://blog.csdn.net/linhuanmars/article/details/20525681
[leetcode] Search in Rotated Sorted Array II,布布扣,bubuko.com
[leetcode] Search in Rotated Sorted Array II
标签:style blog http color os art
原文地址:http://www.cnblogs.com/jdflyfly/p/3815510.html