返回介绍

solution / 2300-2399 / 2364.Count Number of Bad Pairs / README_EN

发布于 2024-06-17 01:03:07 字数 3828 浏览 0 评论 0 收藏 0

2364. Count Number of Bad Pairs

中文文档

Description

You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].

Return_ the total number of bad pairs in _nums.

 

Example 1:

Input: nums = [4,1,3,3]
Output: 5
Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.
The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.
The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.
The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.
The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.
There are a total of 5 bad pairs, so we return 5.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 0
Explanation: There are no bad pairs.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Solutions

Solution 1: Equation Transformation + Hash Table

From the problem description, we know that for any $i < j$, if $j - i \neq nums[j] - nums[i]$, then $(i, j)$ is a bad pair.

We can transform the equation to $i - nums[i] \neq j - nums[j]$. This inspires us to use a hash table $cnt$ to count the occurrences of $i - nums[i]$.

We iterate through the array. For the current element $nums[i]$, we add $i - cnt[i - nums[i]]$ to the answer, then increment the count of $i - nums[i]$ by $1$.

Finally, we return the answer.

The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the array.

class Solution:
  def countBadPairs(self, nums: List[int]) -> int:
    cnt = Counter()
    ans = 0
    for i, x in enumerate(nums):
      ans += i - cnt[i - x]
      cnt[i - x] += 1
    return ans
class Solution {
  public long countBadPairs(int[] nums) {
    Map<Integer, Integer> cnt = new HashMap<>();
    long ans = 0;
    for (int i = 0; i < nums.length; ++i) {
      int x = i - nums[i];
      ans += i - cnt.getOrDefault(x, 0);
      cnt.merge(x, 1, Integer::sum);
    }
    return ans;
  }
}
class Solution {
public:
  long long countBadPairs(vector<int>& nums) {
    unordered_map<int, int> cnt;
    long long ans = 0;
    for (int i = 0; i < nums.size(); ++i) {
      int x = i - nums[i];
      ans += i - cnt[x];
      ++cnt[x];
    }
    return ans;
  }
};
func countBadPairs(nums []int) (ans int64) {
  cnt := map[int]int{}
  for i, x := range nums {
    x = i - x
    ans += int64(i - cnt[x])
    cnt[x]++
  }
  return
}
function countBadPairs(nums: number[]): number {
  const cnt = new Map<number, number>();
  let ans = 0;
  for (let i = 0; i < nums.length; ++i) {
    const x = i - nums[i];
    ans += i - (cnt.get(x) ?? 0);
    cnt.set(x, (cnt.get(x) ?? 0) + 1);
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文