Exercise1.1.29 等值键
2016-01-11 19:55
337 查看
import java.util.Arrays; public class BinarySearch { public static int rank(int key, int[] tar) { Arrays.sort(tar); int low = 0; int high = tar.length - 1; while (low <= high) { int mid = (low + high) / 2; if (key == tar[mid]) { return mid; } else if (key < tar[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } public static int find(int key, int[] array) {// 找出array中所有小于key的个数 int judge = rank(key, array); if (judge != -1) { int index = judge; int i=0; while ( (i=index-1) >= 0 && array[--index] == key) { } return index + 1; } return -1; } public static int count(int key, int[] array) {// 找出array中和key相等的元素 int judge = rank(key, array); if (judge != -1) { int index = judge; int index1 = index; int index2 = index; int sum = 1; int i=0; while ((i=index1-1) >= 0 && array[--index1] == key) { sum++; } while ((i=index2+1) < array.length && array[++index2] == key) { sum++; } return sum; } return -1; } public static void main(String[] args) { int[] array = { 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 5, 6, 7, 8, 9 }; System.out.println("find " + find(9, array)); System.out.println("count " + count(9, array)); } }
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- Linux下Makefile文件详解
- 百度GPSutil
- 10.安装zabbix agent
- 关于程序猿的思考问题
- Leetcode——Contains Duplicate
- 屏幕扩展
- PHP的N个Tip
- 【tyvj1473】校门外的树3
- CSDN 社区大趴-北京站 圆满结束
- openjudge 校门外的树3
- Android中px、sp、dip的区别
- Leetcode——Contains Duplicate
- (eden)Shooting Game
- 三兄弟GETRO、GETTO、SETTO各显神通
- telnet命令
- 用二叉树表示k叉树(left-child-right-sibling)
- Anaconda无法用PIL,我用Pillow替代
- HDOJ 2057A + B Again十六进制问题
- 面试题5:从尾到头打印链表