First Bad Version
Suppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which will return whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
思路上没有什么很难的,注意left + right越界时使用的取均值的方式
int firstBadVersion(int n) {
int left=1, right = n;
int mid = left+(right-left)/2; //here
while(left<right){
mid = left+(right-left)/2;
if(isBadVersion(mid)) right = mid;
else left = mid+1;
}
return left;
}
Arranging Coins
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
Given n, find the total number of full staircase rows that can be formed.
n is a non-negative integer and fits within the range of a 32-bit signed integer.
解法1:二分查找,使用long避免int溢出
int arrangeCoins(int n) {
if(n < 2) return n;
long left = 1;
long right = n;
while (left <= right){
long half = left + (right - left) / 2;
long coins = half * (half + 1) / 2;
if (coins > n) right = half - 1;
else if (coins == n) return half;
else left = half + 1;
}
return (int)right;
}
解法2:求根公式。因为sqrt是一个很耗时的操作,因此效率上反而不如二分查找
int arrangeCoins(int n) {
return (int)((-1 + sqrt(1 + 8 * (long)n)) / 2);
}