再从萌新开始-Leetcode每日题解-667. Beautiful Arrangement II

667Beautiful Arrangement II(Medium

Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement: 
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.

If there are multiple answers, print any of them.

Example 1:

Input: n = 3, k = 1
Output: [1, 2, 3]
Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
Example 2:

Input: n = 3, k = 2
Output: [1, 3, 2]
Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.

Note:

  1. The n and k are in the range 1 <= k < n <= 104.

------------------------------------------------分割线------------------------------------------------------------


题目给定n和k,要求构造一个数组,使得数值包括[1,n]中的所有,并且前后两个的差值的绝对值([|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]) 只有k个不同值。数据量大小为1 <= k < n <= 104,意思就是时间的复杂度要求是O(n^2)以下,讲道理应该是一遍扫描O(n)就可以完成。


分析:

只要找好切入点还是很容易解决的。考虑[1,n]的数组的差值最大可以有几个,该怎么排列:

1. 最大的差值肯定是n-1 = | n - 1 |, 排列可以是 (n,1) 或者是(1,n)。选择其中一种(比如说(1,n)继续往下考虑);

2.那差值 n-2 = | n - 2 | or | (n -1) - 1 |,如果考虑到前面的排列,选择(n , 2)试试,排列就变成了(1, n, 2);

3.同理,顺着这种构造方法下去,我们可以获得拥有m个元素的,并且有m-1个不同差值的排序(1,n,2,n-1,3,…),当m为偶数时,最后一项是n+1-m/2; 当m为奇数时,最后一项是m/2+1;


4.最后一步,就是如何控制差值恰好为k个。以上,我们已经可以通过构造得到k = n-1的情况(也是最大的k值)。我用的方法是,留下最后一个k的位置给1,举个例子来说明吧:如果结构得到了(1, n, 2, n-1 ,3),其中有4个不同差值,如果k等于5,恰好还剩下一个“位置”,那最后一步就是按照升序将剩下的值填充进去,即变成(1, n, 2, n-1, 3, 4, 5, 6 ,7 …, n-1, n-2),让剩下的所有项的差值都为1。



代码:

class Solution{
    public:
        vector<int> constructArray(int n,int k){
            vector<int> ans;
            int left = 1, right = n;
            bool flag = 1; // 1 for left and 0 for right
            while (k > 1){
                if (flag){
                    ans.push_back(left);
                    left++;
                } 
                else{
                    ans.push_back(right);
                    right--;
                } 
                flag = !flag;
                k--;
            } 
            while (left <= right){
                if (flag){
                    ans.push_back(left);
                    left++;
                }else{
                    ans.push_back(right);
                    right--;
                } 
            } 
            return ans;
   
        } 
};  
其中两个while其实可以合并成一个,可以代码会更加简短,虽然降低了可读性。


-------------------------------------------分割线-----------------------------------------------------


题解后面再补。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值