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:
0 <= A.length <= 30000
A.length
is even-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
提示:
0 <= A.length <= 30000
A.length
为偶数-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 }
原文地址:https://www.cnblogs.com/strengthen/p/10090740.html
时间: 2024-11-05 23:25:57