[Swift]LeetCode932. 漂亮數組 | Beautiful Array

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-snukrswr-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:git

For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].github

Given N, return any beautiful array A.  (It is guaranteed that one exists.)數組

Example 1:微信

Input: 4
Output: [2,1,4,3] 

Example 2:app

Input: 5
Output: [3,1,2,5,4]

Note:spa

  • 1 <= N <= 1000

對於某些固定的 N,若是數組 A 是整數 1, 2, ..., N 組成的排列,使得:code

對於每一個 i < j,都不存在 k 知足 i < k < j 使得 A[k] * 2 = A[i] + A[j]htm

那麼數組 A 是漂亮數組。blog

給定 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 }
相關文章
相關標籤/搜索