Skip to content

Commit e53d29b

Browse files
committed
2007_Find_Original_Array_From_Doubled_Array
1 parent 37f54a6 commit e53d29b

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,7 @@ I have solved quite a number of problems from several topics. See the below tabl
260260
|46| **[722. Remove Comments](https://tinyurl.com/y288v3lv)** | [Python](https://tinyurl.com/wu6rdaw/722_Remove_Comments.py), [Swift](https://tinyurl.com/wuja3c4/722_Remove_Comments.swift) | [Art 1](https://tinyurl.com/y56j4p76) | Medium | |
261261
|47| **[443. String Compression](https://tinyurl.com/ybll48vn)** | [Python](https://tinyurl.com/wu6rdaw/443_String_Compression.py), [Swift](https://tinyurl.com/wuja3c4/443_String_Compression.swift) | [Art 1](https://tinyurl.com/y5knbkcd) | Medium | |
262262
|48| **[1525_Number_of_Good_Ways_to_Split_a_String](https://tinyurl.com/yzree7us)** | [Swift](https://tinyurl.com/wuja3c4/1525_Number_of_Good_Ways_to_Split_a_String.swift) | --- | Medium | |
263+
|48| **[2007_Find_Original_Array_From_Doubled_Array](https://tinyurl.com/yhnzl82h)** | [Swift](https://tinyurl.com/wuja3c4/2007_Find_Original_Array_From_Doubled_Array.swift) | --- | Medium | |
263264

264265

265266
</p>
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import Foundation
2+
class Solution {
3+
func findOriginalArray(_ changed: [Int]) -> [Int] {
4+
guard changed.count % 2 == 0 else { return [] }
5+
let changedSorted = changed.sorted()
6+
var countMap = [Int:Int]()
7+
changed.forEach { item in
8+
countMap[item, default: 0] += 1
9+
}
10+
var original = [Int]()
11+
for item in changedSorted {
12+
let key = item * 2
13+
if let _ = countMap[key],
14+
let _ = countMap[item] {
15+
countMap[key]! -= 1
16+
countMap[item]! -= 1
17+
original.append(item)
18+
if let count = countMap[key], count == 0 {
19+
countMap.removeValue(forKey:key)
20+
}
21+
if let count = countMap[item], count == 0 {
22+
countMap.removeValue(forKey:item)
23+
}
24+
}
25+
}
26+
if countMap.keys.count == 0 && original.count * 2 == changed.count {
27+
return original
28+
} else {
29+
return []
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)