Golden programmer interview - face questions 16.11 diving board

topic:

You're using a bunch of pieces of wood diving board. There are two types of wood, wherein the length of the shorter lengths of board Shorter, longer lengths of board length is longer. You must use exactly k pieces of wood. All possible lengths write a method, generating a diving board.

Returning the required length in ascending order.

Example:

Input:
Shorter. 1 =
longer = 2
K =. 3
Output: {3,4,5,6}

analysis:

Simple math problems, i from 0 to k generated for the length

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

program:

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

 

Guess you like

Origin www.cnblogs.com/silentteller/p/12497543.html