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:
- The
n
andk
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 }
分类:
leetcode_array
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!