在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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. The people and seats are represented by an integer from The couples' initial seating is given by Example 1: 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: Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples are already seated side by side. Note:
N 对情侣坐在连续排列的 2N 个座位上,想要牵到对方的手。 计算最少交换座位的次数,以便每对情侣可以并肩坐在一起。 一次交换可选择任意两人,让他们站起来交换座位。 人和座位用 这些情侣的初始座位 示例 1: 输入: row = [0, 2, 1, 3] 输出: 1 解释: 我们只需要交换row[1]和row[2]的位置即可。 示例 2: 输入: row = [3, 2, 0, 1] 输出: 0 解释: 无需交换座位,所有的情侣都已经可以手牵手了。 说明:
Runtime: 8 ms
Memory Usage: 19.1 MB
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 }
|
请发表评论