667. Beautiful Arrangement II

Posted habibah-chang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了667. Beautiful Arrangement II相关的知识,希望对你有一定的参考价值。

问题:

给定一个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的主要内容,如果未能解决你的问题,请参考以下文章

667. Beautiful Arrangement II

667. Beautiful Arrangement II

667. Beautiful Arrangement II

667. Beautiful Arrangement II

leetcode667. Beautiful Arrangement II

[leetcode-667-Beautiful Arrangement II]