leetcode[K-diff Pairs in an Array]//待整理多种解法

解法一:

public class Solution {
    public int findPairs(int[] nums, int k) {
        //因为题目中有下面的要求:
    	//Although we have two 1s in the input, we should only return the number of unique pairs.
    	//所以用Set来存放匹配到的pair
    	Set set = new HashSet<>();
    	//因为      The pairs (i, j) and (j, i) count as the same pair.  所以用二重循环遍历,j从i开始,避免有(i, j) and (j, i)
    	
    	//但是按下面的set的方式,会出现(3,1)和(3,5)都满足的情况,但是后面的(3,5)放不进去,所以先对nums排序
    	Arrays.sort(nums);
    	for(int i = 0; i < nums.length; i++){
    		for(int j = i + 1; j < nums.length; j++){
    			//System.out.println(nums[i] + "    " + nums[j] + "  " + Math.abs(nums[j] - nums[i]));
    			if(Math.abs(nums[j] - nums[i]) == k){
    				if(!set.contains(nums[i])){//保证不会出现pair不是唯一的那种情况
    					//System.out.println(i);
    					set.add(nums[i]);
    				}
    			}
    		}
    	}
    	
    	return set.size();
    }
}


你可能感兴趣的:(LeetCode)