1. 程式人生 > >[Swift Weekly Contest 114]LeetCode954. 二倍數對陣列 | Array of Doubled Pairs

[Swift Weekly Contest 114]LeetCode954. 二倍數對陣列 | Array of Doubled Pairs

Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 <= i < len(A) / 2.

Example 1:

Input: [3,1,3,6]
Output: false

Example 2:

Input: [2,1,2,6]
Output: false

Example 3:

Input: [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

Example 4:

Input: [1,2,4,16,8,4]
Output: false

Note:

  1. 0 <= A.length <= 30000
  2. A.length is even
  3. -100000 <= A[i] <= 100000

給定一個長度為偶數的整數陣列 A,只有對 A 進行重組後可以滿足 “對於每個 0 <= i < len(A) / 2,都有 A[2 * i + 1] = 2 * A[2 * i]” 時,返回 true;否則,返回 false

示例 1:

輸入:[3,1,3,6]
輸出:false

示例 2:

輸入:[2,1,2,6]
輸出:false

示例 3:

輸入:[4,-2,2,-4]
輸出:true
解釋:我們可以用 [-2,-4] 和 [2,4] 這兩組組成 [-2,-4,2,4] 或是 [2,4,-2,-4]

示例 4:

輸入:[1,2,4,16,8,4]
輸出:false

提示:

  1. 0 <= A.length <= 30000
  2. A.length 為偶數
  3. -100000 <= A[i] <= 100000

1100ms
 1 class Solution {
 2     func canReorderDoubled(_ A: [Int]) -> Bool {
 3         var n:Int = A.count
 4         var a:[Int] = [Int](repeating:0,count:n)
 5         for i in 0..<n
 6         {
 7             if A[i] < 0
 8             {
 9                 a[i] = -A[i]*100000000
10             }
11             else
12             {
13                 a[i] = A[i]
14             }
15         }
16         a = a.sorted(by: <)
17         var p:Int = 0
18         var done:[Bool] = [Bool](repeating:false,count:n)
19         for i in 0..<n
20         {
21             if !done[i]
22             {
23                 done[i] = true
24                 while(p < n && (a[p] != a[i] * 2 || done[p]))
25                 {
26                     p += 1
27                 }
28                 if p == n {return false}
29                 done[p] = true
30             }
31         }
32         return true
33     }
34 }