Leetcode 81. Search in Rotated Sorted Array II
来源:互联网 发布:淘宝如何添加全屏代码 编辑:程序博客网 时间:2024/06/07 20:17
/** * 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); }}
0 0
- leetcode题解-33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
- LeetCode 33. Search in Rotated Sorted Array && 81. 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] 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 - 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: Search in Rotated Sorted Array II
- [LeetCode] Search in Rotated Sorted Array II
- ex8
- 七天MFC速成
- exercise9
- Leetcode 81. Search in Rotated Sorted Array II
- Leetcode 33. Search in Rotated Sorted Array
- Leetcode 81. Search in Rotated Sorted Array II
- Find Leaves of Binary Tree
- git的使用
- 分布式一致性算法学习笔记
- 进制
- 二分法(查找、求上界、求下界)
- UML 的九种模型图
- mvc的扩展1
- 封装一个属于自己的mvc框架(2)