码迷,mamicode.com
首页 > 其他好文 > 详细

667. Beautiful Arrangement II

时间:2020-04-19 14:58:40      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:Nging   解法   ack   NPU   --   vector   from   struct   while   

问题:

给定一个n,有数组1~n,

排列该数组,使得数组两两元素之间的差值有k种。

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:
The n and k are in the range 1 <= k < n <= 104.

  

解法:

如有以下数组

[1,2,3,4,5,6,7,8,9,10]

  

n=10, 

k=9的情况,则有

 i, j,  i++,  j--,   i++,  j--,  i++,  j--,   i++, j--,
[1, 10, 2,      9,    3,    8,    4,    7,     5,    6]
k= 9, 8,  7,     6,   5,    4,   3,    2,   1

  

k=6的情况,则有

 j,  i, j--,   i++,  j--,  i++,  i++,   i++, i++,  i++
[10, 1, 9,      2,    8,    3,    4,    5,    6,    7]
k= 9, 8,  7,     6,   5,    1,   1,    1,   1

  

代码参考:

 1 class Solution {
 2 public:
 3     vector<int> constructArray(int n, int k) {
 4         vector<int> res;
 5         if(n<1||k<1)return res;
 6         int i=1, j=n;
 7         while(i<=j){
 8             if(k>1){
 9                 res.push_back(k--%2?i++:j--);
10             }else{
11                 res.push_back(i++);
12             }
13         }
14         return res;
15     }
16 };

 

667. Beautiful Arrangement II

标签:Nging   解法   ack   NPU   --   vector   from   struct   while   

原文地址:https://www.cnblogs.com/habibah-chang/p/12731231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!