leetcode 二分查找
2014-07-05 22:12
302 查看
https://oj.leetcode.com/problems/search-for-a-range/就是一个二分查找,没事练练手
2.另外一种二分查找 beg=0 end=len; end指向的是最后一个元素的后面,
3.第一种方法的递归方式
public class Solution { public int[] searchRange(int[] A, int target) { int a[]=new int[2]; int ans=bSearch(A,target); if(ans==-1) { a[0]=-1; a[1]=-1; return a; } else { int beg=ans; int end=ans; while(beg>=0&&(A[beg]==A[ans])) { beg--; } while(end<A.length&&(A[end]==A[ans])) { end++; } a[0]=beg+1; a[1]=end-1; return a; } } public int bSearch(int[] A,int target) { int low=0; int high=A.length-1; while(low<=high) { int mid =(low+high)/2; if(A[mid]==target) { return mid; } else if(A[mid]>target) { high=mid-1; } else { low=mid+1; } } return -1; } }
2.另外一种二分查找 beg=0 end=len; end指向的是最后一个元素的后面,
public class Solution { public int[] searchRange(int[] A, int target) { int a[]=new int[2]; int ans=bSearch(A,target); if(ans==-1) { a[0]=-1; a[1]=-1; return a; } else { int beg=ans; int end=ans; while(beg>=0&&(A[beg]==A[ans])) { beg--; } while(end<A.length&&(A[end]==A[ans])) { end++; } a[0]=beg+1; a[1]=end-1; return a; } } public int bSearch(int[] A,int target) { int low=0; int high=A.length; while(low<high) //low<high不能等于 { int mid =(low+high)/2; if(A[mid]==target) { return mid; } else if(A[mid]>target) { high=mid; } else { low=mid+1; } } return -1; } }
3.第一种方法的递归方式
public class Solution { public int[] searchRange(int[] A, int target) { int a[]=new int[2]; int ans=bSearch(A,target,0,A.length); if(ans==-1) { a[0]=-1; a[1]=-1; return a; } else { int beg=ans; int end=ans; while(beg>=0&&(A[beg]==A[ans])) { beg--; } while(end<A.length&&(A[end]==A[ans])) { end++; } a[0]=beg+1; a[1]=end-1; return a; } } public int bSearch(int[] A,int target,int low,int high) { while(low<high) { int mid =(low+high)/2; if(A[mid]==target) { return mid; } else if(A[mid]>target) { bSearch(A,target,low,mid); } else { bSearch(A,target,mid,high); } } return -1; } }
相关文章推荐
- leetcode二分查找问题整理
- LeetCode-Find Minimum in Rotated Sorted Array II-旋转排序数组找最小-二分查找
- leetcode 81. Search in Rotated Sorted Array II 旋转数组查找+二分查找
- 154.leetcode Find Minimum in Rotated Sorted Array II(hard)[排序数组 重复元素 二分查找]
- leetcode_35题——Search Insert Position(二分查找)
- ※ Leetcode - Binary Search - 153. Find Minimum in Rotated Sorted Array(二分查找)
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- Leetcode ☞ 35. Search Insert Position 【binary search 二分查找 模板】
- leetcode 633. Sum of Square Numbers 二分查找+勾股定理
- 【LeetCode】69. Sqrt(x) 二分查找实现开平方函数
- Leetcode 二分查找
- leetcode+二分搜索查找,但是有重复数据有点不一样
- LeetCode--二分查找相关算法
- LeetCode-Two Sum-找和等于某个数的两个数-二分查找
- leetcode 35. Search Insert Position-二分查找|递归|非递归
- [leetcode-二分查找]--34. Search for a Range
- leetcode旋转数组查找 二分查找的变形
- leetcode 153. Find Minimum in Rotated Sorted Array 旋转数组(不重复)+二分查找
- LeetCode二分查找总结
- leetcode First Bad Version(二分查找)