667. Beautiful Arrangement II

时间:2020-04-19
本文章向大家介绍667. Beautiful Arrangement II,主要包括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 };

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