LeetCode-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 = 2
Output: 2
Explanation: 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.

Example 2:

Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Note:

  1. The pairs (i, j) and (j, i) count as the same pair.
  2. The length of the array won't exceed 10,000.
  3. All the integers in the given input belong to the range: [-1e7, 1e7].

翻譯:

給定一組數和一個數字 k,你需要找到數組中的 k-不同對的個數。這裏的 k-不同對定義爲一個數字對(i,j),其中 i 和 j 都是數組中的數字並且他們的絕對差是 k。 

例子 1:

輸入: [3, 1, 4, 1, 5], k = 2
輸出: 2
解釋: 這裏的數組中有2-不同對,(1,3)和(3,5)。
儘管我們的輸入中有2個1,我們應該只返回不同的對。

例子 2:

輸入:[1, 2, 3, 4, 5], k = 1
輸出: 4
解釋: 這裏的數組中有4個1-不同對,(1,2),(2,3),(3,4)和(4,5)。

例子 3:

輸入: [1, 3, 1, 5, 4], k = 0
輸出: 1
解釋: 這裏的數組中有1個0-不同對,(1,1)。

注意:

  1. 將(i,j)和(j,i)看成是相同的對。
  2. 數組的長度不超過10,000。
  3. All the integers in the given input belong to the range: [-1e7, 1e7].所有輸入的數字在範圍[-1e7,1e7]之間。


思路:

用map映射將數組中的數字和它們出現的次數進行映射,從頭掃描map,當k=0時,只需要判斷數組中的數字是否出現超過一次,若是,則結果result+1;當k>0時,若當前的數字i加上k還在map中,則滿足絕對差爲k,result+1。


C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution {
public:
	int findPairs(vector<int>& nums, int k) {
		map<int, int> m;
		int res = 0;
		for (int i = 0; i < nums.size(); i++) {
			m[nums[i]]++;
		}
		for (auto a : m) {
			if (k == 0 && a.second > 1)
				res++;
			if (k > 0 && m.count(a.first + k))
				res++;
		}
		return res;
	}
};

int main()
{
	Solution s;
	vector<int> nums = { 1,3,1,5,4 };
	int k = 0;
	int result = s.findPairs(nums, k);
	cout << result << endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章