二分查找,数组去重Java

/**
 * 二分查找
 */
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;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值