Binary search(1) -- First Bad Version, Arranging Coins

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值