二分查找,数组去重Java
2017-05-11 10:19
471 查看
/** * 二分查找 */ package algorithms; /** * @author * * @time 2017年5月9日 下午3:48:29 */ public class BinarySearch { public static int rank(int key, int[] a){ //数组必须是有序的 int head = 0; int tail = a.length - 1; while(head <= tail){ //被查找的键要么不存在,要么必然存在于a[head..tail]之中 int mid = head + (tail - head)/2; if(key < a[mid]){ tail = mid - 1; }else if(key > a[mid]){ head = mid + 1; }else{ return mid; } } return -1; } //递归法 public static int binarySearch(int[] a,int head,int tail,int key){ //数组必须是有序的 // int head = 0; // int tail = a.length - 1; if(head <= tail){ //被查找的键要么不存在,要么必然存在于a[head..tail]之中 int mid = head + (tail - head)/2; if(key < a[mid]){ tail = mid - 1; }else if(key > a[mid]){ head = mid + 1; }else{//key == a[mid] return mid; } return binarySearch(a,head,tail,key); } return -1; } public static void main(String[] args) { // int[] a = {10,20,30,40,50,60}; // int i = rank(40,a); // System.out.println(i); // if(i>-1){ // System.out.println(a[i]); // } // System.out.println(binarySearch(a,0,a.length-1,40)); int[] a = {10,20,30,30,30,40,40,40,40,50,60}; int[] b = duplicateRemoval(a);//去重后的数组 } /** * 数组去重 */ private static int[] duplicateRemoval(int[] a) { // int num = count(a); int[] b = new int[a.length-num]; int count = 0; b[0] = a[0]; for(int i = 0;i < a.length-1;i++){ if(a[i]==a[i+1]){ count ++; }else{ b[i+1-count] = a[i+1]; } } return b; } /** * 计算重复数量 */ private static int count(int[] a) { int count = 0; for(int i = 0;i < a.length-1;i++){ if(a[i]==a[i+1]){ count ++; } } return count; } }
相关文章推荐
- Java数组遍历、求最大值、选择排序、冒泡排序、二分查找
- Java数组二分查找
- 【Java】数组二分查找元素
- java基础知识4--数组,排序,二分查找
- 有序表查询之一:java实现整型数组二分查找
- 栋哥带你学Java数组排序和二分查找
- java数组中二分查找Demo范例
- java基础复习--数组的二分查找
- JAVA数组排序——二分(折半)查找
- 重学java之随机数组二分查找
- Java实现数组二分查找及递归二分查找
- java面试题9--数组高级-二分查找
- Java数组与二分查找
- java数组的封装以及二分查找
- JAVA基础复习十三-StringBuffer、数组排序、二分查找、自动拆装箱
- java数组排序,二分查找
- Java数组中的排序和二分查找
- 【Java版本】二分查找&数字在排序数组中出现的次数
- 黑马程序员_Java基础_04数组main函数args详解、数组排序、二分查找实例
- JavaSE第三十六讲:Java数组查找方式及二分查找分析