• [day009]面试题 16.11. 跳水板


    面试题 16.11. 跳水板

    Difficulty: 简单

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

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

    示例:

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

    提示:

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

    Solution 1

    ​class Solution {
    public:
        vector<int> divingBoard(int shorter, int longer, int k) {
            vector<int> v;
            if(k != 0){
                set<int> s;
                for(int i = 0;i <= k;++i){
                    s.insert(i*longer+(k-i)*shorter);
                }
                for(auto num : s){
                    v.push_back(num);
                }
            }
            return v;
        }
    };
    

    思路

    利用set自动排序的功能过滤下,不过set底层是红黑树,维护这棵树平衡的时间复杂度可不低。

    Solution 2

    class Solution {
    public:
        vector<int> divingBoard(int shorter, int longer, int k) {
            vector<int> vec;
            if(k == 0)
                return vec;
            if(shorter == longer) {
                vec.push_back(k*shorter);
                return vec;
            }
            else {
                for(int i = 0;i <= k;++i){
                    vec.push_back(shorter * (k - i) + longer * i);
    
                }
                return vec;
            }
        }
    };
    

    思路

    纯数学题了,可以证明随着长板增长,板长整体递增(一次函数),且不会重合,需要注意k=0和两板长度相等的特殊情况。

  • 相关阅读:
    BZOJ 3033 太鼓达人(DFS+欧拉回路)
    HDU 5121 Just A Mistake
    HDU 5120 Intersection
    HDU 5119 Happy Matt Friends
    HDU 5117 Fluorescent
    BZOJ 1088: [SCOI2005]扫雷Mine
    Codeforces 994 C
    BZOJ 2242: [SDOI2011]计算器
    HDU 4609 3-idiots
    算法笔记--FFT && NTT
  • 原文地址:https://www.cnblogs.com/Swetchine/p/13269769.html
Copyright © 2020-2023  润新知