leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 39 】2021-10-18 - 762.Number Stream to Intervals #56

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

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)

jerry9926 commented 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;
}

复杂度分析

Bingbinxu commented 3 years ago

思路 二分法 代码

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)

hellowxwworld commented 2 years ago
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;
}