|
| 1 | +class MultiSet { |
| 2 | + constructor() { |
| 3 | + this.countMap = new Map() |
| 4 | + this.valueList = [] |
| 5 | + } |
| 6 | + remove(value) { |
| 7 | + if(!this.countMap.has(value)) return false |
| 8 | + let index = binarySearch(this.valueList, value) |
| 9 | + if (this.countMap.get(value) === 1) { |
| 10 | + this.valueList.splice(index, 1) |
| 11 | + this.countMap.delete(value) |
| 12 | + } else { |
| 13 | + this.countMap.set(value, (this.countMap.get(value) || 0) - 1) |
| 14 | + } |
| 15 | + return true |
| 16 | + } |
| 17 | + add(value) { |
| 18 | + let index = binarySearch(this.valueList, value) |
| 19 | + if (index < 0) { |
| 20 | + this.valueList.splice(-index - 1, 0, value) |
| 21 | + this.countMap.set(value, 1) |
| 22 | + } else { |
| 23 | + this.countMap.set(value, this.countMap.get(value) + 1) |
| 24 | + } |
| 25 | + } |
| 26 | + has(value) { |
| 27 | + return this.countMap.has(value) |
| 28 | + } |
| 29 | + get max() { |
| 30 | + return this.valueList[this.valueList.length - 1] |
| 31 | + } |
| 32 | + get min() { |
| 33 | + return this.valueList[0] |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +function binarySearch(arr, val) { |
| 38 | + let l = 0, r = arr.length |
| 39 | + while( l < r ) { |
| 40 | + const mid = Math.floor((l + r) / 2) |
| 41 | + if(arr[mid] < val) { |
| 42 | + l = mid + 1 |
| 43 | + } else { |
| 44 | + r = mid |
| 45 | + } |
| 46 | + } |
| 47 | + if(arr[l] !== val) return -(l + 1) |
| 48 | + |
| 49 | + return l |
| 50 | +} |
| 51 | +/** |
| 52 | + * @param {number[]} nums |
| 53 | + * @return {number} |
| 54 | + */ |
| 55 | +const sumImbalanceNumbers = function (nums) { |
| 56 | + let n = nums.length, res = 0; |
| 57 | + for (let i = 0; i < n; i++) { |
| 58 | + let tree = new MultiSet(), cnt = 0; |
| 59 | + tree.add(nums[i]); |
| 60 | + for (let j = i + 1; j < n; j++) { |
| 61 | + let x = nums[j]; |
| 62 | + if (!tree.has(x)) { |
| 63 | + tree.add(x); |
| 64 | + cnt++; |
| 65 | + if (tree.has(x - 1)) cnt--; |
| 66 | + if (tree.has(x + 1)) cnt--; |
| 67 | + } |
| 68 | + res += cnt; |
| 69 | + } |
| 70 | + } |
| 71 | + return res; |
| 72 | +} |
0 commit comments