跳过正文
  1. Posts/

leetcode 532. K-diff Pairs in an Array (找差为k的数对)

·2 分钟

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:

1Input: [3, 1, 4, 1, 5], k = 2
2Output: 2
3Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
4Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

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

Example 3:

1Input: [1, 3, 1, 5, 4], k = 0
2Output: 1
3Explanation: 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].

思路:由于重复的只算一次,所以存两个set,分别为nums[i]和nums[i]+k.复杂度O(nlgn)

对于k=0的情况特殊处理,因为可能自己和自己组成一对…所以k=0可以排序然后找出现次数大于一次的元素,也是O(nlgn)

总体复杂度O(nlgn)

另外需要注意的是,两个数的绝对值可能是负数…..k<0返回0。。。

脑回路真是不一样。。。都绝对值了。。还负数。。。?出题人觉得没考虑到负数是考虑不周到?

然而我只觉得出题人傻逼。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2017年04月05日 星期三 14时25分00秒
 4File Name :532.cpp
 5 ************************************************ */
 6class Solution {
 7    public:
 8    int findPairs(vector<int>& nums, int k) {
 9        int siz = nums.size();
10        int res = 0 ;
11        if (k<0) return 0;
12        if (k==0)
13        {
14        sort(nums.begin(),nums.end());
15        nums.push_back(1E8);
16        for ( int i = 1 ; i < siz ; i++)
17        {
18            if (nums[i]==nums[i-1]&&nums[i]!=nums[i+1]) res++;
19        }
20        return res;
21        }
22        set<int>a;
23        set<int>b;
24        for ( int i = 0 ; i < siz;  i++)
25        {
26        a.insert(nums[i]+k);
27        b.insert(nums[i]);
28        }
29        for ( auto &it:a)
30        {
31        if (b.count(it)) res++;
32        }
33        return res;
34    }
35};

相关文章

今日头条2017秋招笔试_1

·2 分钟
头条校招(今日头条2017秋招真题) 题目描述 头条的2017校招开始了!为了这次校招,我们组织了一个规模宏大的出题团队。每个出题人都出了一些有趣的题目,而我们现在想把这些题目组合成若干场考试出来。在选题之前,我们对题目进行了盲审,并定出了每道题的难度系数。一场考试包含3道开放性题目,假设他们的难度从小到大分别为a, b, c,我们希望这3道题能满足下列条件:

今日头条笔试题-木棒拼图(数学)

·2 分钟
有一个由很多木棒构成的集合,每个木棒有对应的长度,请问能否用集合中的这些木棒以某个顺序首尾相连构成一个面积大于 0 的简单多边形且所有木棒都要用上,简单多边形即不会自交的多边形。

今日头条笔试题-最大映射(贪心)

·3 分钟
有 n 个字符串,每个字符串都是由 A-J 的大写字符构成。现在你将每个字符映射为一个 0-9 的数字,不同字符映射为不同的数字。这样每个字符串就可以看做一个整数,唯一的要求是这些整数必须是正整数且它们的字符串不能有前导零。现在问你怎样映射字符才能使得这些字符串表示的整数之和最大? 输入描述:每组测试用例仅包含一组数据,每组数据第一行为一个正整数 n , 接下来有 n 行,每行一个长度不超过 12 且仅包含大写字母 A-J 的字符串。 n 不大于 50,且至少存在一个字符不是任何字符串的首字母。 输出描述:输出一个数,表示最大和是多少。 输入例子: 2 ABC BCA 输出例子: 1875 一开始看漏了首位不能映射到0的条件…直接贪了..结果发现不太对…