重排序数组,使相邻两个数的绝对值之差不一样 Beautiful Arrangement II

问题:ui

Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement: 
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.this

If there are multiple answers, print any of them.spa

Example 1:code

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:three

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:ip

  1. The n and k are in the range 1 <= k < n <= 104.

解决:rem

【题意】给定整数n和k,列表[a1, a2, a3, ... , an] = [1, 2, 3, ..., n],从新排列,使得列表[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 刚好包含k个不一样整数。it

① io

元素差最多的个数是n-1个,这个n-1的构成也很容易发现,较大的数和较小的数交替造成的序列就知足要求class

例如,咱们假设n= 6,k = 5,那么这个序列就是 6 1 5 2 4 3 造成的k个元素差为: 5 4 3 2 1 (反向也是能够的 即 1 6 2 5 3 4)

若k不等于n-1,咱们只须要按上述规律造成知足k-1的序列,剩余序列按递减序便可(剩余的差值都为1)。 
假设n = 6,k = 4,咱们获得的序列便是: 1 6 2 5 4 3。 

class Solution { //7ms     public int[] constructArray(int n, int k) {         int[] res = new int[n];         int left = 1;         int right = n;         for (int i = 0;left <= right;i ++){             res[i] = k > 1 ? (k -- % 2 == 0 ? right -- : left ++) : left ++;//从最大和最小数轮流取值         }         return res;     } }

相关文章
相关标签/搜索