Skip to content

Commit fe87f17

Browse files
committed
Add solution #1362
1 parent 3ec9ffc commit fe87f17

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,255 LeetCode solutions in JavaScript
1+
# 1,256 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1036,6 +1036,7 @@
10361036
1359|[Count All Valid Pickup and Delivery Options](./solutions/1359-count-all-valid-pickup-and-delivery-options.js)|Hard|
10371037
1360|[Number of Days Between Two Dates](./solutions/1360-number-of-days-between-two-dates.js)|Easy|
10381038
1361|[Validate Binary Tree Nodes](./solutions/1361-validate-binary-tree-nodes.js)|Medium|
1039+
1362|[Closest Divisors](./solutions/1362-closest-divisors.js)|Medium|
10391040
1365|[How Many Numbers Are Smaller Than the Current Number](./solutions/1365-how-many-numbers-are-smaller-than-the-current-number.js)|Easy|
10401041
1366|[Rank Teams by Votes](./solutions/1366-rank-teams-by-votes.js)|Medium|
10411042
1368|[Minimum Cost to Make at Least One Valid Path in a Grid](./solutions/1368-minimum-cost-to-make-at-least-one-valid-path-in-a-grid.js)|Hard|

solutions/1362-closest-divisors.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 1362. Closest Divisors
3+
* https://leetcode.com/problems/closest-divisors/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer num, find the closest two integers in absolute difference whose product
7+
* equals num + 1 or num + 2.
8+
*
9+
* Return the two integers in any order.
10+
*/
11+
12+
/**
13+
* @param {number} num
14+
* @return {number[]}
15+
*/
16+
function closestDivisors(num) {
17+
const pair1 = findClosestPair(num + 1);
18+
const pair2 = findClosestPair(num + 2);
19+
20+
return Math.abs(pair1[1] - pair1[0]) <= Math.abs(pair2[1] - pair2[0]) ? pair1 : pair2;
21+
22+
function findClosestPair(target) {
23+
let minDifference = Infinity;
24+
let pair = [];
25+
26+
for (let divisor = 1; divisor <= Math.sqrt(target); divisor++) {
27+
if (target % divisor === 0) {
28+
const complement = target / divisor;
29+
const difference = Math.abs(complement - divisor);
30+
if (difference < minDifference) {
31+
minDifference = difference;
32+
pair = [divisor, complement];
33+
}
34+
}
35+
}
36+
37+
return pair;
38+
}
39+
}

0 commit comments

Comments
 (0)