leetcode 532. K-diff Pairs in an Array
来源:互联网 发布:旅游saas平台源码 编辑:程序博客网 时间:2024/05/22 15:35
leetcode 532. K-diff Pairs in an Array 下面这种解法TLE
public class Solution { public int findPairs(int[] nums, int k) { if(nums==null||nums.length==0||k<0) return 0; int len = nums.length; int res = 0; Set<Integer> isPassed = new HashSet<Integer>(); for(int i=0;i<len;i++){ if(isPassed.contains(nums[i])){ continue; } Set<Integer> matched = new HashSet<Integer>(); for(int j=i+1;j<len;j++){ if(isPassed.contains(nums[j])) continue; if(nums[j]-nums[i]==k||nums[j]-nums[i]==-k){ matched.add(nums[j]); } } res += matched.size(); isPassed.add(nums[i]); } return res; }}
相同的数聚合在一起,就可以了啊。
public class Solution { public int findPairs(int[] nums, int k) { if(nums==null||nums.length==0||k<0) return 0; int len = nums.length; int res = 0; Map<Integer,Integer> map = new HashMap<Integer, Integer>(); for(int i:nums){ map.put(i, map.getOrDefault(i, 0)+1); } for(Map.Entry<Integer, Integer> entry:map.entrySet()){ if(k==0){ if(entry.getValue()>=2){ res++; } }else{ if(map.containsKey(entry.getKey()+k)){ res++; } } } return res; }}
阅读全文
0 0
- LeetCode K-diff Pairs in an Array
- LeetCode : K-diff Pairs in an Array
- leetCode-K-diff Pairs in an Array
- 【Leetcode】532. K-diff Pairs in an Array
- 532. K-diff Pairs in an Array ------Leetcode
- 【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-algorithms 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
- 对Python 函数修饰符的一些理解
- 自定义异常链处理
- Java
- <NOIP> 29 . P2089 烤鸡
- JavaScript创建对象的七种方式
- leetcode 532. K-diff Pairs in an Array
- 线程池
- 小程序开发之坑一 -- ios不显示tabBar的文字
- java基础二
- Android Studio Error:Failed to resolve: com.android.support:appcompat-v7:25.1.0
- Keyboard Row
- Web自动化之Headless Chrome概览
- redis-压缩列表
- java基础--多线程