-
Notifications
You must be signed in to change notification settings - Fork 0
/
1818.绝对差值和.js
82 lines (73 loc) · 1.7 KB
/
1818.绝对差值和.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* @lc app=leetcode.cn id=1818 lang=javascript
*
* [1818] 绝对差值和
*/
// @lc code=start
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var minAbsoluteSumDiff = function (nums1, nums2) {
const mod = 1000000007;
const sum = nums1.reduce((sum, cur, i) => {
return (sum + Math.abs(cur - nums2[i])) % mod;
}, 0);
nums1Copy = Array.from(nums1).sort((a, b) => a - b);
const length = nums1.length;
let max = 0;
const binarySearch = (arr, target) => {
let l = 0,
r = length - 1;
while (l + 1 < r) {
let mid = Math.floor((l + r) / 2);
if (arr[mid] < target) {
l = mid;
} else if (arr[mid] > target) {
r = mid;
} else {
return mid;
}
}
if (Math.abs(arr[l] - target) > Math.abs(arr[r] - target)) {
return r;
} else {
return l;
}
};
let n = length;
function findclosed(val, nums1) {
let left = 0,
right = n - 1;
while (left + 1 < right) {
const mid = Math.floor((left + right) / 2);
if (nums1[mid] == val) {
left = mid;
right = mid;
break;
} else if (nums1[mid] < val) {
left = mid;
} else {
right = mid;
}
}
let maxleft = nums1[left];
let minright = nums1[right];
if (Math.abs(maxleft - val) > Math.abs(minright - val)) {
return minright;
} else {
return maxleft;
}
}
for (let i = 0; i < length; i++) {
const element = nums2[i];
const index = binarySearch(nums1Copy, element);
max = Math.max(
max,
Math.abs(nums1[i] - element) - Math.abs(nums1Copy[index] - element)
);
}
return (sum - max + mod) % mod;
};
// @lc code=end