20220209LiCode刷题
给你一个整数数组 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]
code:
class Solution { public int countKDifference(int[] nums, int k) { int count = 0; for(int i=0;i<nums.length;i++) { for(int j = i+1;j<nums.length;j++) { if(Math.abs(nums[i]-nums[j])==k) { ++count; } } } return count; } }
执行结果:
通过
显示详情
添加备注
执行用时:8 ms, 在所有 Java 提交中击败了14.29%的用户
内存消耗:41 MB, 在所有 Java 提交中击败了5.34%的用户
通过测试用例:237 / 237