Leetcode-Array 1
来源:互联网 发布:老男孩linux培训 编辑:程序博客网 时间:2024/05/22 15:31
编程基础太弱,所以加强联系,现在的算法在时空复杂度上还有待改进。
K-diff Pairs in an Array
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 = 2Output: 2Explanation: 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.
思路:首先进行排序,然后依次进行遍历,对每一个数组元素,一种方法可以使用第二个指针,找到diff = k
的位置;另一种方法是由于nums
已经排序,所以利用二分的思想减少时间复杂度。
个人代码实现:
public class Solution { public int findPairs(int[] nums, int k) { Arrays.sort(nums); int count=0; for(int i=0;i<nums.length;i++){ if(i>0 && nums[i]==nums[i-1]) continue; int index=binarySearch(nums,nums[i],i+1,nums.length-1,k); if (index!=-1) { count++; } } return count; } public int binarySearch(int[] nums,int num,int lo,int hi,int k){ int mid=(lo+hi)/2; if(lo>hi) return -1; // lo == hi is OK if(nums[mid]-num==k) return mid; else if(nums[mid]-num>k) { return binarySearch(nums,num,lo,mid-1,k); }else{ return binarySearch(nums,num,mid+1,hi,k); } }}
0 0
- Leetcode-Array 1
- LeetCode (1) Merge Sorted Array
- [leetcode][array] Rotate Array
- LeetCode:Array
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- Array-Leetcode
- LeetCode Array
- Leetcode-array
- leetcode array
- 变量
- 常见几种滤波器的比较
- 第五章 5-2 画笔
- 聚合果项目ssm经验总结
- 《C++ primer plus》附录G:STL方法与函数(二) 学习笔记
- Leetcode-Array 1
- 对于\和/的小问题:证明路径中可以混合使用斜杠和反斜杠
- php经典算法
- [交互 杂题] Codeforces Gym 100307 NEERC 13 I. Interactive Interception
- proxy
- 努力
- 小白训练Day4
- 扑克牌游戏
- 使用nasm实现Fibonacci数列