您的位置:首页 > 大数据 > 人工智能

532. K-diff Pairs in an Array

2017-08-07 12:57 441 查看
1.题目

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2

Output: 2

Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).

Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1

Output: 4

Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0

Output: 1

Explanation: There is one 0-diff pair in the array, (1, 1).

Note:

The pairs (i, j) and (j, i) count as the same pair.

The length of the array won’t exceed 10,000.

All the integers in the given input belong to the range: [-1e7, 1e7].

2.分析

  这道题其实并不难,理解了题意后。可以利用Map的key唯一性,来进行计数,但是这样就有了不必要的空间开销。于是参考了一下别人的解法,看半天,没太理解,只是根据所理解的写了一个遍历计数并去重的方法。

3.解题

解法一:

public class Solution {
public int findPairs(int[] nums, int k) {
// 边界处理
if(nums==null){
return 0;
}
ArrayList<Integer>set = resultSet(nums);
HashMap<Integer,Integer>map = new HashMap<Integer,Integer>();
if(set==null){
return 0;
}
int[]result = new int[set.size()];int flag = 0;
for(int i:set){
result[flag] = i;
flag++;
}
Arrays.sort(result);

int count = 0;
for(int i=0;i<result.length-1;i++){
for(int j=i+1;j<result.length;j++){
if(result[j]-result[i]==k){
map.put(result[i],result[j]);
}
}
}
return map.size();
}
public ArrayList<Integer> resultSet(int[]nums){
ArrayList<Integer>set = new ArrayList<Integer>();

if(nums==null){
return set;
}
for(int tem:nums){
set.add(tem);
}
return set;
}
}


解法二:

public class Solution {
public int findPairs(int[] nums, int k) {
// 边界处理
if(nums==null){
return 0;
}
int len = nums.length;
int count = 0;
Arrays.sort(nums);

for(int i=0;i<len;i++){
for(int j=i+1;j<len;j++){
if(nums[j]-nums[i]==k){
count++;

while(j+1<len&&nums[j+1]==nums[j]){
j++;
}
}
}
while(i+1<len&&nums[i+1]==nums[i]){
i++;
}
}
return count;
}
}


4.总结

  尝试解题的同时,参考别人解题,对比之下,发现差异与优劣,一定要弄清楚每一步的实现- -。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: