[leetcode]二分查找总结
2014-08-02 13:37
387 查看
Search for a Range
1.最简单的想法,用最普通的二分查找,找到target,然后向左右扩张,大量的重复的target,就会出现O(n)效率。class Solution { public int[] searchRange(int[] A, int target) { int ans[]=new int[2]; int a= bserch(A,target); if(a==-1) {ans[0]=-1;ans[1]=-1; return ans;} //left int b=a-1; while(b>=0&&A[b]==target) b--; ans[0]=b+1; b=a+1; while(b<=A.length-1&&A[b]==target) b++; ans[1]=b-1; return ans; } public int bserch(int A[],int target) { int low=0; int end=A.length-1; while(low<=end) { int mid=(low+end)>>1; if(A[mid]==target) return mid; else if(A[mid]<target) low=mid+1; else end=mid-1; } return -1; } }
2.二分查找加入第一个大的位置(上届),第一个大于等于它的位置(下界)
class Solution { public int[] searchRange(int[] A, int target) { int ans[]=new int[2]; int a= bserch(A,target); if(a==-1) {ans[0]=-1;ans[1]=-1; return ans;} //left int b=a-1; while(b>=0&&A[b]==target) b--; ans[0]=b+1; b=a+1; while(b<=A.length-1&&A[b]==target) b++; ans[1]=b-1; return ans; } //其实难点就是A[mid]==target,如何调整low和high public int bserch(int A[],int target) { int low=0; int end=A.length-1; while(low<=end) { int mid=(low+end)>>1; if(A[mid]==target) return mid; else if(A[mid]<target) low=mid+1; else end=mid-1; } return -1; } //第一个大于target的 public int upperbound(int A[],int target) // the first one larger than target { int low=0; int end=A.length-1; while(low<=end) { int mid=(low+end)>>1; if(A[mid]>target) end=mid-1; else low=mid+1; } return low; } public int lowbound(int A[],int target) // the first one larger or equal target { int low=0; int end=A.length-1; while(low<=end) { int mid=(low+end)>>1; if(A[mid]>=target) end=mid-1; else low=mid+1; } return low; } }
相关文章推荐
- [LeetCode]Search Insert Position (二分查找总结) Java Version
- leetcode第十四周解题总结--二分查找
- [LeetCode] Serch Insert Position (总结二分查找) Java version
- LeetCode-二分查找面试题目总结
- leetcode第十五周解题总结--二分查找(二)
- LeetCode二分查找总结
- LeetCode:Search Insert Position,Search for a Range (二分查找,lower_bound,upper_bound)
- Leetcode 二分查找 Search Insert Position
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- [算法][LeetCode]Search a 2D Matrix——二维数组的二分查找
- 【二分查找】学习总结
- 二分查找和字符串基本知识总结
- 查找(二):二分查找----<学习总结>
- 对排序的总结&&二分查找
- leetcode旋转数组查找 二分查找的变形
- LeetCode @ Search Insert Position 二分查找
- Leetcode 二分查找 Search a 2D Matrix
- 三大查找算法总结:二分查找,分块查找和哈希表查找。
- 查找算法总结之顺序查找、二分查找、静态树查找
- 二分查找总结