Last active
December 4, 2019 07:47
-
-
Save greenchiu/818c6f667ec112f3c0dadb8cc4f5a5de to your computer and use it in GitHub Desktop.
Finding smallest common element in two arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func Solution(_ nums1:[Int], _ nums2: [Int]) -> Int? { | |
let set: Set<Int> = Set(nums1) | |
var result: Int? | |
for element in nums2 { | |
if set.contains(element) { | |
if let currentMin = result { | |
result = min(element, currentMin) | |
continue | |
} | |
result = element | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
題目:在兩個陣列找出最小的共同值,陣列是任意排序 (non-sorted)。
時間太短沒有問太多細節
當天有用暴力解法兩個 for loop 解 -> O(n^2)
後來簡化到 set + sorted array -> O(nlogn)
到這邊有收到提示說可以不用 sort ,當下有點轉不過來,後來因為時間不足到這邊就結束了
後來想一想應該是 set + one loop 就可以結束,可以將時間複雜度降低到 O(n)