Skip to content

Commit 099dbff

Browse files
authored
Update 765-couples-holding-hands.js
1 parent 44eac72 commit 099dbff

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

765-couples-holding-hands.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,35 @@ const minSwapsCouples = function (row) {
7272
}
7373
}
7474

75+
// another
76+
77+
/**
78+
* @param {number[]} row
79+
* @return {number}
80+
*/
81+
const minSwapsCouples = function (row) {
82+
let res = 0
83+
const n = row.length
84+
const ptn = Array(n).fill(0), pos = Array(n).fill(0)
85+
86+
for(let i = 0; i < n; i++) {
87+
ptn[i] = (i % 2 === 0 ? i + 1 : i - 1)
88+
pos[row[i]] = i
89+
}
90+
91+
for (let i = 0; i < n ;i++) {
92+
for (let j = ptn[pos[ptn[row[i]]]]; i != j; j = ptn[pos[ptn[row[i]]]]) {
93+
swap(row, i, j);
94+
swap(pos, row[i], row[j]);
95+
res++;
96+
}
97+
}
98+
99+
return res
100+
101+
function swap(arr, i, j) {
102+
const val = arr[i]
103+
arr[i] = arr[j]
104+
arr[j] = val
105+
}
106+
}

0 commit comments

Comments
 (0)