★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-ecrdqolr-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swapconsists of choosing any two people, then they stand up and switch seats.git
The people and seats are represented by an integer from 0
to 2N-1
, the couples are numbered in order, the first couple being (0, 1)
, the second couple being (2, 3)
, and so on with the last couple being (2N-2, 2N-1)
.github
The couples' initial seating is given by row[i]
being the value of the person who is initially sitting in the i-th seat.微信
Example 1:ide
Input: row = [0, 2, 1, 3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person.
Example 2:spa
Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples are already seated side by side.
Note:code
len(row)
is even and in the range of [4, 60]
.row
is guaranteed to be a permutation of 0...len(row)-1
.N 對情侶坐在連續排列的 2N 個座位上,想要牽到對方的手。 計算最少交換座位的次數,以便每對情侶能夠並肩坐在一塊兒。 一次交換可選擇任意兩人,讓他們站起來交換座位。htm
人和座位用 0
到 2N-1
的整數表示,情侶們按順序編號,第一對是 (0, 1)
,第二對是 (2, 3)
,以此類推,最後一對是 (2N-2, 2N-1)
。blog
這些情侶的初始座位 row[i]
是由最初始坐在第 i 個座位上的人決定的。get
示例 1:
輸入: row = [0, 2, 1, 3] 輸出: 1 解釋: 咱們只須要交換row[1]和row[2]的位置便可。
示例 2:
輸入: row = [3, 2, 0, 1] 輸出: 0 解釋: 無需交換座位,全部的情侶都已經能夠手牽手了。
說明:
len(row)
是偶數且數值在 [4, 60]
範圍內。row
是序列 0...len(row)-1
的一個全排列。1 class Solution { 2 func minSwapsCouples(_ row: [Int]) -> Int { 3 var row = row 4 var res:Int = 0 5 var n:Int = row.count 6 for i in stride(from:0,to:n,by:2) 7 { 8 if row[i + 1] == (row[i] ^ 1) 9 { 10 continue 11 } 12 res += 1 13 for j in (i + 1)..<n 14 { 15 if row[j] == (row[i] ^ 1) 16 { 17 row[j] = row[i + 1] 18 row[i + 1] = row[i] ^ 1 19 break 20 } 21 } 22 } 23 return res 24 } 25 }
8ms
1 class Solution { 2 func minSwapsCouples(_ row: [Int]) -> Int { 3 guard row.count > 2 else { 4 return 0 5 } 6 var row = row 7 var numberOfSwaps: Int = 0 8 for seat in stride(from:0, to: row.count - 1, by: 2) { 9 let current = row[seat] 10 let other = row[seat + 1] 11 if current == other ^ 1 { continue } 12 numberOfSwaps += 1 13 for j in (seat+2)..<row.count { 14 if row[j] == current ^ 1 { 15 row.swapAt(j, seat + 1) 16 } 17 } 18 } 19 return numberOfSwaps 20 } 21 }
12ms
1 class Solution { 2 func minSwapsCouples(_ row: [Int]) -> Int { 3 var row = row 4 var res = 0 5 for i in 0..<row.count { 6 guard i % 2 == 0 else { continue } 7 let target = row[i] % 2 == 0 ? row[i] + 1 : row[i] - 1 8 if row[i + 1] == target { continue } 9 for j in i+2..<row.count { 10 if row[j] == target { 11 (row[i+1], row[j]) = (row[j], row[i+1]) 12 res += 1 13 } 14 } 15 } 16 return res 17 } 18 }