667. Beautiful Arrangement II

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.

If there are multiple answers, print any of them.

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:

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

题目含义:给定整数n和k,列表[a1, a2, a3, ... , an] = [1, 2, 3, ..., n],重新排列,使得列表[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 恰好包含k个不同整数。

 

思路:

给定n那么k最大为n-1,假设这k个数字是 n-1,n-2,n-3...1,所以数列可以是1,n-1,2,n-2,....,

比如给定n=9 k=8则数列可以是9 1 8 2 7 3 6 4 5,可以看出这组数据差值是8 7 6 5 4 3 2 1

比如给定n=9 k=4则数列可以是9 1 8 2 3 7 4 6 5,可以看出这组数据差值是8 7 6 1 1 1 1 1

1     public int[] constructArray(int n, int k) {
2         int[] res = new int[n];
3         int left = 1, right = n;
4         for (int i = 0; left <= right; i++) {
5             res[i] = k > 1 ? (k-- % 2 == 0 ? right-- : left++) : left++;  //从最大和最小数轮流取值.k为偶数时从右拿,k为奇数时候从左拿
6         }
7         return res;
8     }

 

posted @   daniel456  阅读(285)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示