zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    Oracle常用系统查询SQL
    easyui中使用的遮罩层
    EasyUI相同的Tab只打开一个(即EasyUI方法的调用方法)
    jQueryEasyUI创建菜单主页
    linux 的环境变量的配置文件
    angular reactive form
    svn代码回滚
    golang restful api
    golang embedded structs
    Angular Multiple HTTP Requests with RxJS
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12731231.html
Copyright © 2011-2022 走看看