• 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 };
  • 相关阅读:
    Elasticsearch 缓存总结
    ElasticSearch-集群
    HTTP协议详解
    HTTPS总结
    ElasticSearch--Document
    正排索引和倒排索引
    线上OOM排查步骤总结
    线程池-四种拒绝策略总结
    netty篇-练手
    netty篇-UDP广播
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12731231.html
Copyright © 2020-2023  润新知