Leetcode 81. Search in Rotated Sorted Array II
2016-12-27 07:25
399 查看
/** * similar with Search in Rotated Sorted Array, * the difference is we need to take care of the case such as * 1, 1, ..., 1, 1 here, 1 is the duplicate element. * The algorithm discussed in the Search in Rotated Sorted Array should start at 2 in this case. * Therefore, we 'remove' the duplicates at the beginning of the array, then apply Search in Rotated Sorted Array. * Running time for the worst case should be o(n). */ public class Solution { // find the index of the minimum public int searchMin (int low, int[] nums) { int high = nums.length-1, mid = 0; while (low < high) { mid = (low+high)/2; if (nums[mid] > nums[high]) low = mid + 1; else high = mid; } return low; } // binary search for sorted array public boolean binarySearch (int[] nums, int low, int high, int target) { int mid = 0; while (low < high) { mid = (low+high)/2; if (nums[mid] < target) low = mid+1; else high = mid; } return (nums[low] == target) ? true : false; } public boolean search(int[] nums, int target) { int i=0, imin = 0; // skip duplicates at the beginning of the array if (nums[i] == nums[nums.length-1]) { for (i=1; i<nums.length; i++) if (nums[i-1] != nums[i]) break; } // cases such as [1], [1,1,1] arrays that only contain duplicates (*) if (i == nums.length) return (nums[i-1] == target); imin = searchMin(i, nums); if (target <= nums[nums.length-1]) return binarySearch(nums, imin, nums.length-1, target); return binarySearch(nums, 0, imin-1, target); } }
相关文章推荐
- [Leetcode] 81. Search in Rotated Sorted Array II
- LeetCode 81. Search in Rotated Sorted Array II
- [Leetcode 81, Medium] Search in Rotated Sorted Array II
- 【LeetCode】81. Search in Rotated Sorted Array II (2 solutions)
- leetcode 81:Search in Rotated Sorted Array II
- 81. Search in Rotated Sorted Array II Leetcode Python
- 【LEETCODE】81-Search in Rotated Sorted Array II [Python]
- leetcode 81 : Search in Rotated Sorted Array II
- leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法
- LeetCode 81 Search in Rotated Sorted Array II
- leetcode[81]Search in Rotated Sorted Array II
- LeetCode(33)(81) Search in Rotated Sorted Array I II
- leetcode_81——Search in Rotated Sorted Array II(二分查找)
- LeetCode81——Search in Rotated Sorted Array II
- [LeetCode]81 Search in Rotated Sorted Array II
- [leetcode] 81.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 81. Search in Rotated Sorted Array II