zy2317878的博客

博观约取,厚积薄发。多读书,多看报,多做事,多交流。

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。即可。这也是一个小技巧。

程序分析

略。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zy2317878/article/details/79962871
文章标签: LeetCode Array
个人分类: LeetCode
上一篇LeetCode-442. Find All Duplicates in an Array
下一篇LeetCode-495. Teemo Attacking
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭