Skip to content

Instantly share code, notes, and snippets.

@fredriccliver
Created September 19, 2021 10:18
Show Gist options
  • Save fredriccliver/c1551f0594582801c765750c976cd4ac to your computer and use it in GitHub Desktop.
Save fredriccliver/c1551f0594582801c765750c976cd4ac to your computer and use it in GitHub Desktop.
import Foundation
import Glibc
/*
Find the first unique number (value, not index) heading firstly
If there isn't return -1
value, count set.
order by value asc
return the value has 1 count
if not, return -1
*/
public func solution(_ A : inout [Int]) -> Int {
// the value : (count, appearedAt)
var countArr:[Int:(Int,Int)] = [:]
for i in 0...A.count-1 {
let val = A[i]
if countArr[val] != nil {
countArr[val]! = (countArr[val]!.0 + 1, countArr[val]!.1)
}else{
countArr[val] = (1,i)
}
}
countArr = countArr.filter{ item in
return item.value.0 == 1
}
let sorted = countArr.sorted(by: {
$0.value.1 < $1.value.1
})
if(sorted.count == 0){
return -1
}
return sorted[0].key
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment