leetcode[K-diff Pairs in an Array]//待整理多种解法
来源:互联网 发布:流量赚钱软件 编辑:程序博客网 时间:2024/06/06 18:54
解法一:
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<Integer> 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(); }}
阅读全文
1 0
- leetcode[K-diff Pairs in an Array]//待整理多种解法
- LeetCode K-diff Pairs in an Array
- LeetCode : K-diff Pairs in an Array
- leetCode-K-diff Pairs in an Array
- K-diff Pairs in an Array问题及解法
- LeetCode刷题【Array】 K-diff Pairs in an Array
- 【Leetcode】532. K-diff Pairs in an Array
- 532. K-diff Pairs in an Array ------Leetcode
- K-diff Pairs in an Array leetcode 532
- 【leetcode】532. K-diff Pairs in an Array
- [Leetcode]532. K-diff Pairs in an Array
- [LeetCode]532. K-diff Pairs in an Array
- Leetcode 532 K-diff Pairs in an Array
- [leetcode]-532 K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- leetcode题解-532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- [LeetCode]532. K-diff Pairs in an Array
- 很好的php采集函数(自己备份)
- Log everything in your working time
- 欢迎使用CSDN-markdown编辑器
- Python中常用的爬虫框架
- 用 jsoup做爬虫采集站点(一)
- leetcode[K-diff Pairs in an Array]//待整理多种解法
- Java异常堆栈的查看方法
- Android快速使用Gradle实现多渠道打包
- 微信小程序之底部导航栏(一)
- Xposed之helloworld
- 自动备份MySQL数据库
- React组件refs详解
- Luogu P1331 海战
- spring-1