程序员面试金典-面试题 16.11. 跳水板

题目:

你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为shorter,长度较长的木板长度为longer。你必须正好使用k块木板。编写一个方法,生成跳水板所有可能的长度。

返回的长度需要从小到大排列。

示例:

输入:
shorter = 1
longer = 2
k = 3
输出: {3,4,5,6}

分析:

简单的数学题,i从0到k生成的长度为

(k - i) * shorter + i * longer;

程序:

class Solution {
    public int[] divingBoard(int shorter, int longer, int k) {
        if(k == 0)
            return new int[]{};
        if(shorter == longer)
            return new int[]{shorter * k};
        int[] res = new int[k+1];
        for(int i = 0; i < k+1; ++i){
            res[i] = (k - i) * shorter + i * longer;
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12497543.html