[Swift]LeetCode932. 漂亮数组 | Beautiful Array
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9865478.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
For some fixed N
, an array A
is beautiful if it is a permutation of the integers 1, 2, ..., N
, such that:
For every i < j
, there is no k
with i < k < j
such that A[k] * 2 = A[i] + A[j]
.
Given N
, return any beautiful array A
. (It is guaranteed that one exists.)
Example 1:
Input: 4
Output: [2,1,4,3]
Example 2:
Input: 5
Output: [3,1,2,5,4]
Note:
1 <= N <= 1000
对于某些固定的 N
,如果数组 A
是整数 1, 2, ..., N
组成的排列,使得:
对于每个 i < j
,都不存在 k
满足 i < k < j
使得 A[k] * 2 = A[i] + A[j]
。
那么数组 A
是漂亮数组。
给定 N
,返回任意漂亮数组 A
(保证存在一个)。
示例 1:
输入:4 输出:[2,1,4,3]
示例 2:
输入:5 输出:[3,1,2,5,4]
提示:
1 <= N <= 1000
16ms
1 class Solution { 2 func beautifulArray(_ N: Int) -> [Int] { 3 var a:[Int] = [Int](repeating: 0,count: N) 4 dfs(1, 0, N, &a,0) 5 for i in 0..<N 6 { 7 a[i] += 1 8 } 9 return a 10 } 11 //深度优先搜索。DFS即Depth First Search. 12 //对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次 13 func dfs(_ d:Int,_ m:Int,_ n: Int,_ a:inout [Int],_ off:Int) -> Int 14 { 15 var off = off 16 if m >= n {return off} 17 if m + d >= n 18 { 19 a[off] = m 20 off += 1 21 return off 22 } 23 for i in 0..<2 24 { 25 off = dfs(d*2, m+d*i, n, &a, off) 26 } 27 return off 28 } 29 }
16ms
1 class Solution { 2 func beautifulArray(_ N: Int) -> [Int] { 3 var res: [Int] = [] 4 res.append(1) 5 while res.count < N { 6 var temp: [Int] = [] 7 for i in res { 8 if i * 2 - 1 <= N { 9 temp.append(i * 2 - 1) 10 } 11 } 12 for i in res { 13 if i * 2 <= N { 14 temp.append(i * 2) 15 } 16 } 17 res = temp 18 } 19 return res 20 } 21 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了