LeetCode 2006. Count Number of Pairs With Absolute Difference K【数组/哈希表】

Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.

The value of |x| is defined as:

  • x if x >= 0.
  • -x if x < 0.

Example 1:

Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]
- [1,2,2,1]

Example 2:

Input: nums = [1,3], k = 3
Output: 0
Explanation: There are no pairs with an absolute difference of 3. 

Example 3:

Input: nums = [3,2,1,5,4], k = 2
Output: 3
Explanation: The pairs with an absolute difference of 2 are:
- [3,2,1,5,4]
- [3,2,1,5,4]
- [3,2,1,5,4]

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 100
  • 1 <= k <= 99

题意:给你一个整数数组 nums 和一个整数 k ,请你返回数对 (i, j) 的数目,满足 i < j 且 |nums[i] - nums[j]| == k 。

|x| 的值定义为:

  • 如果 x >= 0 ,那么值为 x 。
  • 如果 x < 0 ,那么值为 -x 。

解法1 暴力双重循环

很简单的题目,数据范围很小,用双重循环也能过。时间复杂度为 O ( n 2 ) O(n^2) O(n2) ,空间复杂度为 O ( 1 ) O(1) O(1) :

//C++ version
class Solution {
public:
    int countKDifference(vector<int>& nums, int k) {
        int ans = 0;
        for (int i = 0, n = nums.size(); i < n; ++i)
            for (int j = i + 1; j < n; ++j) 
                if (abs(nums[i] - nums[j]) == k)
                    ++ans;
        return ans;
    }
};
//执行用时:12 ms, 在所有 C++ 提交中击败了87.21% 的用户
//内存消耗:12.1 MB, 在所有 C++ 提交中击败了43.34% 的用户

解法2 哈希表

1. 两数之和差不多的题目、差不多的做法。算法的时间复杂度为 O ( n ) O(n) O(n) ,空间复杂度为 O ( 100 ) O(100) O(100) :

//C++ version
class Solution {
public:
    int countKDifference(vector<int>& nums, int k) {
        int cnt[102] = {0}, ans = 0;
        for (int i = 0, n = nums.size(); i < n; ++i) {
            if (nums[i] - k >= 0) ans += cnt[nums[i] - k];
            if (nums[i] + k <= 100) ans += cnt[nums[i] + k];
            ++cnt[nums[i]]; 
        }
        return ans;
    }
};
//执行用时:8 ms, 在所有 C++ 提交中击败了96.71% 的用户
//内存消耗:11.9 MB, 在所有 C++ 提交中击败了98.40% 的用户
上一篇:Unity引用外部DLL后打包发布需要注意的一些问题


下一篇:[CF-Edu113]D. Inconvenient Pairs