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;
}
}