532. 数组中的K-diff数对
532. 数组中的K-diff数对
给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k.
示例 1:
输入: [3, 1, 4, 1, 5], k = 2
输出: 2
解释: 数组中有两个 2-diff 数对, (1, 3) 和 (3, 5)。
尽管数组中有两个1,但我们只应返回不同的数对的数量。
示例 2:
输入:[1, 2, 3, 4, 5], k = 1
输出: 4
解释: 数组中有四个 1-diff 数对, (1, 2), (2, 3), (3, 4) 和 (4, 5)。
示例 3:
输入: [1, 3, 1, 5, 4], k = 0
输出: 1
解释: 数组中只有一个 0-diff 数对,(1, 1)。
注意:
数对 (i, j) 和数对 (j, i) 被算作同一数对。
数组的长度不超过10,000。
所有输入的整数的范围在 [-1e7, 1e7]。
解题思路:双指针,前后指针之差如果等于k,则count++;因为数组是排好序的,只要保证与前一个有效数对不相等即可,如果差大了,前指针后移,否则后指针后移,同时要考虑前指针后移不能超过后指针,如果即将超过,说明没有与后指针匹配的前指针,此时后指针应后移一位。
class Solution {
public int findPairs(int[] nums, int k) {
if(k<0)
return 0;
Arrays.sort(nums);
int count=0;
int pre=0;
int post=1;
int prenum=Integer.MIN_VALUE;
while(post<nums.length)
{
if(nums[post]-nums[pre]==k)
{
if(nums[pre]!=prenum)
{
count++;
prenum=nums[pre];
}
post++;
pre++;
}
else if(nums[post]-nums[pre]>k)
{
if(pre==post-1)
{
pre++;
post++;
}else
pre++;
}
else
post++;
}
return count;
}
}
---------------------
作者:还没想好1234
来源:CSDN
原文:https://blog.csdn.net/qq_33420835/article/details/81981463
版权声明:本文为博主原创文章,转载请附上博文链接!

浙公网安备 33010602011771号