二分搜索

Sqrt(x)

 

Implement int sqrt(int x).

Compute and return the square root of x.

static long biSearch(long l, long h, long x, int dep) {
        long y = (l + h) / 2;
        if (dep > 100) return y;
        if (y * y > x) {
            return biSearch(l, y, x, dep + 1);
        } else if (y * y < x) {

            return biSearch(y, h, x, dep + 1);
        } else {
            return y;
        }

    }

    static public int sqrt(int x) {
        return Math.abs((int)biSearch(0L, (long)(x + 1),(long) x, 0));
    }

Search in Rotated Sorted Array

 

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.



如果是递增数组向右循环移位形成的数组有一个重要的性质:
设pos是数组a={23,34,41,52,4,8,13,20 }的分界点,有pos=3,a[pos]=52,则
1)对于pos及其右边的元素都大于pos左边的元素;
2)只有pos点满足:a[pos] > a[pos + 1]。

int findPos(int[] a, int lo, int hi) {
        if (hi - lo == 1 || hi - lo == 2 && a[lo] > a[hi-1]) return lo;
        if (lo >= hi) return -1;
        int mid = (hi + lo) / 2;
        if (a[mid] > a[mid + 1]) return mid;
        else {
            if (a[mid] > a[lo]) {
                return findPos(a, mid + 1, hi);
            } else if (a[mid] < a[hi - 1]) {
                return findPos(a, lo, mid);
            } else return -1;
        }
    }


    int biSearch(int[] a, int x, int lo, int hi) {
        if (lo >= hi) return -1;
        int mid = (hi + lo) / 2;
        if (a[mid] == x) return mid;
        else if (a[mid] > x)
            return biSearch(a, x, lo, mid);
        else
            return biSearch(a, x, mid + 1, hi);
    }

    //23,24,4,5,17
    int indexOf(int[] array, int target) {
        if (array == null || array.length == 0) return -1;
        if (array[0] <=array[array.length - 1])
            return biSearch(array, target, 0, array.length);
        else {
            int pos = findPos(array, 0, array.length);

            int i = biSearch(array, target, 0, pos + 1);
            int j = biSearch(array, target, pos, array.length);
            if (i != -1) return i;
            if (j != -1) return j;
            return -1;
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值