Skip to content

Instantly share code, notes, and snippets.

@fengyitsai
Created January 10, 2020 16:24
Show Gist options
  • Save fengyitsai/dfc896accfe959cfef322ee333215ca5 to your computer and use it in GitHub Desktop.
Save fengyitsai/dfc896accfe959cfef322ee333215ca5 to your computer and use it in GitHub Desktop.
765. Couples Holding Hands
class Solution {
func minSwapsCouples(_ row: [Int]) -> Int {
var indices = row
var row = row
for i in 0..<row.count {
indices[row[i]] = i
}
var result = 0
for i in stride(from: 1, to: row.count-2, by: 2) {
let a = row[i-1]
let b = row[i]
if isCouple(a,b) {
continue
} else {
let p = pair(to: b)
row.swapAt(i-1,indices[p])
indices.swapAt(p,a)
result += 1
}
}
return result
}
func isCouple(_ a: Int, _ b: Int) -> Bool {
return pair(to: a) == b
}
func pair(to n:Int) -> Int {
if n % 2 == 1 {
return n - 1
} else {
return n + 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment