LintCode 1796: K-Difference

1796. K-Difference

In this challenge, you will be given an array of integers, each unique within the array, and an integer representing a target difference. Determine the number of pairs of elements in the array that have a difference equal to the target difference.

For example, consider the array [1, 3, 5] and a target difference 2. There are two pairs:[1, 3] and [3, 5],that have the target difference.you must return an integer count of the number of pairs within a having a difference of k.

 

Example

Example 1:

 

Input: nums = [1, 3, 5, 7], target = 2

Output: 3

Explanation:

3 - 1 = 2

5 - 3 = 2

7 - 5 = 2

Example 2:

 

Input: nums = [7, 2, 6], target = 2 

Output: 0

Explanation:

no pair have a difference of k 

Notice

5 <= n <= 10^5.

Each element of a,a[i] <= 2 * 10^9.

Each a[i] is unique within a.

1 <= k <= 10^9.

解法1:双指针
 

class Solution {
public:
    /**
     * @param nums: a integer array
     * @param target: 
     * @return: return a integer
     */
    int KDifference(vector<int> &nums, int target) {
        int count = 0;
        int len = nums.size();
        int start = 0, end = 1;

        sort(nums.begin(), nums.end());

        while(end < len) {
            int diff = nums[end] - nums[start];
            if (diff == target) {
                count++;
                end++;
            } else if (diff < target) {
                end++;
            } else {
                start++;
            }
        }
        
        return count;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值