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