667. Beautiful Arrangement II

来源:互联网 发布:notepad++ mac 编辑:程序博客网 时间:2024/06/05 04:24

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 = 1Output: [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 = 2Output: [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种。想法是首先前k个数构造成[1, n, 2, n-1....]这种形式,这样前k-1个差值的绝对值就是n-1,n-2,n-3...剩下的数接上剩下的,使的剩下的差值都为1。比如n=6,k=3时,就是1,6,5,4,3,2。


代码:

class Solution {public:    vector<int> constructArray(int n, int k) {        vector<int> ans(n);        int i, l = 1, r = n;        for(i = 1; i <= k; ++i) {            if(i & 1) ans[i-1] = l++;            else ans[i-1] = r--;        }        if(i & 1) {            for(i; i <= n; ++i) {                ans[i-1] = r--;            }        }        else {            for(i; i <= n; ++i) {                ans[i-1] = l++;            }        }        return ans;    }};





阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 淡然图片 淡然的图片 淡然若水 淡然123 淡然处之 淡然的意思 淡然是什么意思 女主淡然低调学霸型校园 淡然若水图片 综穿淡然人生 琴心淡然作品 女主淡然低调古言婚后 做个淡然坚强女子图片 综穿之淡然人生 女主睿智通透随性淡然 农女王妃有点田花淡然 浓情淡如你 第十个橘猫 淡白舌 兰蔻精准淡斑臻白精华乳 淡竹根 淡竹 淡笑不羽作品 运夫 淡笑不羽 星际未来之受运记 淡笑不羽 淡色蔷薇 月经少色淡怎么回事 月经量少色淡怎么调理 月经量少色淡是什么原因 太色了 一起色 色怕色 淡色 就色 月经提前量少色淡 女性过性活后出淡色血 排卵期突然排除一股淡色血水 月经推迟 量少 色淡 淡菜子 淡菜汤 淡菜的做法 淡菜图片