Open azl397985856 opened 3 years ago
mark
function tripleInversion(nums) {
if (!nums.length || nums.length === 1) return 0;
let count = 0;
while (nums.length > 1) {
let last = nums.pop();
let tripleLast = last * 3;
for (let el of nums) {
if (el > tripleLast) count++;
}
}
return count;
}
思路 二分法 代码
int solve(vector<int>& nums) {
map<int, int> dict;
int res = 0;
for (auto& num : nums)
{
auto it = dict.upper_bound(3*num);
if (it != dict.end())
{
for (auto it1 = it; it1 != dict.end(); it1++)
res += it1->second;
}
if (dict.count(num) > 0)
dict[num]++;
else dict[num] = 1;
}
return res;
}
复杂度 时间复杂度:O(NlogN) 空间复杂度:O(N)
int countBiggerThan(vector<int>& nums, int target) {
int size = nums.size();
int l = 0;
int r = size - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (nums[mid] < target)
l = mid + 1;
else if (nums[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return size - l;
}
int numberStreamToIntervals(vector<int>& nums) {
int res = 0;
for (int i = 1; i < nums.size(); ++i) {
vector<int> a(nums.begin(), nums.begin() + i);
sort(a.begin(), a.end());
res += countBiggerThan(a, nums[i] * 3);
}
return res;
}
762.Number Stream to Intervals
入选理由
暂无
题目地址
https://binarysearch.com/problems/Triple-Inversion
前置知识
题目描述
Constraints
n ≤ 100,000 where n is the length of nums Example 1 Input nums = [7, 1, 2] Output 2 Explanation We have the pairs (7, 1) and (7, 2)