二分查找之变形
2011-10-31 15:14
483 查看
//寻找一个数,找到刚好比他小的数。
比如-1 1 1 1 2 ~~~
如果要找1,那么返回的是-1的位置0。
如果1开头,那么返回位置-1.
用同样的方法来找刚好比其大的数。
这两个函数可以用于对在[b , e]区间里面的数进行计数。比如POJ 2413题。不过要注意数列是从 1, 2, 3开始的。不是一般的从1 1 2 3开始。
粘个java的代码。
比如-1 1 1 1 2 ~~~
如果要找1,那么返回的是-1的位置0。
如果1开头,那么返回位置-1.
int lbs(int *a, int n, int v){ int b = 0, e = n, m; while (b < e){ m = b + ((e - b) >> 1); if (a[m] >= v) e = m; else b = m + 1; } while (0 <= m && a[m] >= v) --m; return m; }
用同样的方法来找刚好比其大的数。
int rbs(int *a, int n, int v){ int b = 0, e = n, m; while (b < e){ m = b + ((e - b) >> 1); if (a[m] <= v) b = m + 1; else e = m; } while (m < n && a[m] <= v) ++m; return m; }
这两个函数可以用于对在[b , e]区间里面的数进行计数。比如POJ 2413题。不过要注意数列是从 1, 2, 3开始的。不是一般的从1 1 2 3开始。
粘个java的代码。
import java.io.*; import java.util.*; import java.math.*; public class Main { public static int leftBinarySearch(BigInteger [] w, int n, BigInteger v){ int b = 0, e = n, m = 0, re; while (b < e){ m = (b + e) >> 1; re = w[m].compareTo(v); if (re >= 0) e = m; else b = m + 1; } while (0 <= m && w[m].compareTo(v) >= 0) --m; return m; } public static int rightBinarySearch(BigInteger [] w, int ms, BigInteger v){ int b = 0, e = ms, m = 0, re; while (b < e){ m = b + ((e - b) >> 1); re = w[m].compareTo(v); if (re <= 0) b = m + 1; else e = m; } while (m < ms && w[m].compareTo(v) <= 0) ++m; return m; } public static void main(String[] args) throws Exception { int [] a = new int[50]; final int ms = 500; BigInteger [] ar = new BigInteger[ms]; ar[0] = BigInteger.ONE; ar[1] = BigInteger.valueOf(2); a[0] = 1; a[1] = 2; a[2] = 3; for (int i = 2; i <= 42; ++i){ a[i] = a[i-1] + a[i-2]; ar[i] = BigInteger.valueOf(a[i]); } for (int i = 43; i < ms; ++i){ ar[i] = ar[i-1].add(ar[i-2]); } BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = cin.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); int i = 0; while (i < line.length() && (' ' == line.charAt(i) || '0' == line.charAt(i))) ++i; if (i == line.length()) break; BigInteger aa = new BigInteger(st.nextToken()); BigInteger bb = new BigInteger(st.nextToken()); int from = leftBinarySearch(ar, ms, aa); int to = rightBinarySearch(ar, ms, bb); //System.out.println("" + from + ' ' + to); System.out.println("" + (to - from - 1)); } } }
相关文章推荐
- 微软的二分查找变形题
- 二分查找及其变形整理
- 二分查找极其变形算法
- poj 1064 二分查找变形—判定并找到可行解
- 51nod 1279 扔盘子 (二分查找的变形)
- 【小米笔试题】二分查找算法的变形
- 算法-分割有序数组后查值-二分查找的变形
- 二分查找变形
- 二分查找及其变形总结
- 二分查找及其几个变形
- 最长上升子序列变形题-二分查找DP
- 你真的能搞定二分查找吗 — 二分查找及变形
- Find Peak Element——二分查找的变形
- 一种二分查找变形
- 2014-04-04 循环递增数组查找元素(二分变形思想,百度面试题)
- 二分查找变形1
- 二分查找及其变形
- leetcode旋转数组查找 二分查找的变形
- 二分查找及其变形算法
- 二分查找及其变形