LeetCode-667. Beautiful Arrangement II

Description

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.

Solution 1(C++)

class Solution {
public:
    vector<int> constructArray(int n, int k) {
        vector<int> res(1,1);
        int flag=0, dif=k, temp;
        while(res.size()<n){
            temp=res[res.size()-1]; 
            if(dif>=1){
                if(0==flag) {res.push_back(temp+dif); flag=1;}
                else {res.push_back(temp-dif); flag=0;}
                dif--;
            }
            else{
                res.push_back(res.size()+1);
            }
        }
        return res;
    }
};

Solution 2(C++)

class Solution {
public:
    vector<int> constructArray(int n, int k) {
        vector<int> res;
        int i = 1, j = n;
        while (i <= j) {
            if (k > 1) res.push_back(k-- % 2 ? i++ : j--);
            else res.push_back(i++);
        }
        return res;
    }
};

算法分析

1~n个数,任意两个数最小的差为1,最大的差为n-1,题目要求差有k个不同,这k个不同的差值,最小也为1,最大也为n-·1。题目要求给出一种可能的方法即可,所以,尝试差值为1,2,3,…,k-1.那么数列:1,k,2,2,k-1,…直到前后两个数差值为1.这个数列的个数为k,那么比n个数少的,直接在后面补齐即可。

此外,要注意,插值从k-1降到1,这是前面的数列构成,后面的额外补充的数列,添加res.size()+1。即可。这也是一个小技巧。

程序分析

略。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值