Skip to content

Commit ea2cdd3

Browse files
committed
Create 1679. K 和数对的最大数目.js
1 parent a291a59 commit ea2cdd3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

1679. K 和数对的最大数目.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var maxOperations = function (nums, k) {
7+
nums.sort((a, b) => a - b);
8+
function binarySearch(i, j, v) {
9+
while (i <= j) {
10+
const mid = Math.ceil((i + j) / 2);
11+
if (nums[mid] === v) {
12+
return mid;
13+
} else if (nums[mid] < v) {
14+
i = mid + 1;
15+
} else {
16+
j = mid - 1;
17+
}
18+
}
19+
return -1;
20+
}
21+
22+
let result = 0;
23+
let i = 0;
24+
while (nums.length > 1 && i < nums.length - 1) {
25+
if (nums[i] >= k) {
26+
break;
27+
}
28+
29+
if (k - nums[i] >= nums[i]) {
30+
const target = binarySearch(i + 1, nums.length - 1, k - nums[i]);
31+
if (target !== -1) {
32+
nums.splice(target, 1);
33+
nums.splice(i, 1);
34+
result++;
35+
continue;
36+
}
37+
}
38+
i++;
39+
}
40+
41+
return result;
42+
};

0 commit comments

Comments
 (0)