leetcode 667. Beautiful Arrangement II

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.
这道题需要细细观测,绝对值符号一定要看清楚!
然后根据题意可知,给你个数n和k,要求排列出的等差的绝对值的种类数有k个,如果答案有多种,我们只列出一个。
OK,既然不要求求出所有的排列组合,那我们就用一种方法,瞄准一个方向前进即可。试想,假如k=n-1,如何排列能让排列满足每个等差绝对值都不同呢?如果把数组劈成两半,然后把后一半倒过来,等距离插入前半段中,就是这样:1,n,2,n-1,3,n-2,你会发现数之间的差绝对值为,n-1,n-2,n-3,n-4…..,正好满足n-1个不同值的要求。
OK,如果要求k=n-2呢?不要慌,这时候只需要将前半端左移一个距离就行了,像这样:1,2,n,3,n-1,4,n-2……你可以列举n=6,n=7来证明它的正确性。
这就是其中一种解法,很清晰,很聪明,根据这种解法,我们可写出下面的代码:

class Solution {
public:
    vector<int> constructArray(int n, int k) {
        vector<int> res(n, 0);
        int l = 1;
        int r = n;

        for (int i = 0; i <= (n-1-k); ++i)
            res[i] = l++;
        for (int i = l-1; i < res.size(); i = i+2){
            res[i] = r;
            if (i+1 < res.size())
                res[i+1] = l;
            else
                break;
            r--;
            l++;
        }
        return res;        
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值