Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a9fc8f6

Browse files
Create 3017-count-the-number-of-houses-at-a-certain-distance-ii.js
1 parent 9dfb722 commit a9fc8f6

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number} n
3+
* @param {number} x
4+
* @param {number} y
5+
* @return {number[]}
6+
*/
7+
var countOfPairs = function (n, x, y) {
8+
if (x > y) {
9+
;[x, y] = [y, x]
10+
}
11+
const res = new Array(n).fill(0)
12+
for (let i = 1; i <= n; ++i) {
13+
res[0] += 2 // go left and right
14+
res[Math.min(i - 1, Math.abs(i - y) + x)]-- // reach 1 then stop
15+
res[Math.min(n - i, Math.abs(i - x) + 1 + n - y)]-- // reach n then stop
16+
res[Math.min(Math.abs(i - x), Math.abs(y - i) + 1)]++ // reach x then split
17+
res[Math.min(Math.abs(i - x) + 1, Math.abs(y - i))]++ // reach y then split
18+
let r = Math.max(x - i, 0) + Math.max(i - y, 0)
19+
res[r + Math.floor((y - x) / 2)]-- // i -> x -> y <- x
20+
res[r + Math.floor((y - x + 1) / 2)]-- // i -> y -> x <- y
21+
}
22+
for (let i = 1; i < n; ++i) {
23+
res[i] += res[i - 1]
24+
}
25+
return res
26+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /