Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

差的绝对值为 K 的数对数目 #144

Open
yankewei opened this issue Feb 9, 2022 · 1 comment
Open

差的绝对值为 K 的数对数目 #144

yankewei opened this issue Feb 9, 2022 · 1 comment
Labels
哈希表 题目包含哈希表解法 数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Feb 9, 2022

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

|x|的值定义为:

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

示例 1:

输入:nums = [1,2,2,1], k = 1
输出:4
解释:差的绝对值为 1 的数对为:
- [(1),(2),2,1]
- [(1),2,(2),1]
- [1,(2),2,(1)]
- [1,2,(2),(1)]

示例 2:

输入:nums = [1,3], k = 3
输出:0
解释:没有任何数对差的绝对值为 3 。

示例 3:

输入:nums = [3,2,1,5,4], k = 2
输出:3
解释:差的绝对值为 2 的数对为:
- [(3),2,(1),5,4]
- [(3),2,1,(5),4]
- [3,(2),1,5,(4)]

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-number-of-pairs-with-absolute-difference-k
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei
Copy link
Owner Author

yankewei commented Feb 9, 2022

遍历

func countKDifference(nums []int, k int) int {
    var r int

    for i := 0; i < len(nums); i++ {
        for j := i; j < len(nums); j++ {
            diff := nums[i] - nums[j]
            if diff == k || diff == -k {
                r++
            }
        }
    }

    return r
}

哈希

func countKDifference(nums []int, k int) int {
    var r int
    m := make(map[int]int)
    for _, v := range nums {
        m[v]++
    }

    for _, v := range nums {
	r += m[v+k]
	r += m[v-k]
	m[v]--
    }

    return r
}

哈希优化版

func countKDifference(nums []int, k int) int {
    var r int
    m := make(map[int]int)
    for _, v := range nums {
	r += m[v+k]
	r += m[v-k]
	m[v]++
    }
    return r
}

@yankewei yankewei added 哈希表 题目包含哈希表解法 简单 题目难度为简单 数组 题目类型为数组 labels Feb 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
哈希表 题目包含哈希表解法 数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant