Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3f9e5b3

Browse files
committed
Add solution #765
1 parent 3bbbd50 commit 3f9e5b3

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

0765-couples-holding-hands.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 765. Couples Holding Hands
3+
* https://leetcode.com/problems/couples-holding-hands/
4+
* Difficulty: Hard
5+
*
6+
* There are n couples sitting in 2n seats arranged in a row and want to hold hands.
7+
*
8+
* The people and seats are represented by an integer array row where row[i] is the ID of the
9+
* person sitting in the ith seat. The couples are numbered in order, the first couple being
10+
* (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).
11+
*
12+
* Return the minimum number of swaps so that every couple is sitting side by side. A swap
13+
* consists of choosing any two people, then they stand up and switch seats.
14+
*/
15+
16+
/**
17+
* @param {number[]} row
18+
* @return {number}
19+
*/
20+
function minSwapsCouples(row) {
21+
const n = row.length / 2;
22+
const partner = new Array(2 * n);
23+
const position = new Array(2 * n);
24+
25+
for (let i = 0; i < 2 * n; i++) {
26+
partner[i] = i % 2 === 0 ? i + 1 : i - 1;
27+
position[row[i]] = i;
28+
}
29+
30+
let swaps = 0;
31+
for (let i = 0; i < 2 * n; i += 2) {
32+
const current = row[i];
33+
const expected = partner[current];
34+
const nextPerson = row[i + 1];
35+
36+
if (nextPerson !== expected) {
37+
row[i + 1] = expected;
38+
row[position[expected]] = nextPerson;
39+
position[nextPerson] = position[expected];
40+
position[expected] = i + 1;
41+
swaps++;
42+
}
43+
}
44+
45+
return swaps;
46+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,7 @@
579579
762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
580580
763|[Partition Labels](./0763-partition-labels.js)|Medium|
581581
764|[Largest Plus Sign](./0764-largest-plus-sign.js)|Medium|
582+
765|[Couples Holding Hands](./0765-couples-holding-hands.js)|Hard|
582583
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|
583584
784|[Letter Case Permutation](./0784-letter-case-permutation.js)|Medium|
584585
790|[Domino and Tromino Tiling](./0790-domino-and-tromino-tiling.js)|Medium|

0 commit comments

Comments
 (0)