16.11. 跳水板

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

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

示例:

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

0 < shorter <= longer
0 <= k <= 100000

解题思路

我的方法比较粗暴,例如题目所给的实例题:
	shorter = 1
	longer = 2
	k = 3
	输出: {
   3,4,5,6}
k = 3有分配给shorter和longer的情况有哪几种?

0 3(两种)--->shorter = 0,longer = 3或shorter = 3,longer = 0
1 2(两种)--->shorter = 1,longer = 2或shorter = 2,longer = 1
2 1(两种)--->shorter = 2,longer = 1或shorter = 1,longer = 2
3 0(两种)--->shorter = 3,longer = 0或shorter = 0,longer = 3

可见存入数组的元素就有{
   6,3,5,4,4,5,6,3}去重后就是 {
   3,4,5,6}

代码

class Solution {
   
    public int[] divingBoard(int shorter, int longer, int k) {
   
        int i = 0,j=0;
		//如果 = 0时返回 [],  new int[0]返回的就是首地址[]
        if(k == 0){
   
            return new int[0];
        }
        //数组,包含重复
        ArrayList<Integer> list = new ArrayList();
        for(i = 0,j=k; i<=k && j>=0; i++,j--){
   
            list.add(i*shorter+j*longer);
            list.add(j*longer+i*longer);
        }
        //去重后
       Set<Integer> set = new HashSet(list);
       //存入Object数组
       Object[] arrays = set.toArray();
       //排序
       Arrays.sort(arrays);
       //Object-->Integer
       Integer[] integers = new Integer[arrays.length];
       for ( i = 0; i < arrays.length; i++) {
   
           integers[i] = Integer.parseInt(arrays[i].toString());
        }
        //Integer--->int
        int result[] = new int[integers.length];
        for( i = 0; i<integers.length; i++){
   
            result[i] = integers[i];
        }

       return result;
    
    }
}

测试