描述

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:

The pairs (i, j) and (j, i) count as the same pair.

The length of the array won't exceed 10,000.

All the integers in the given input belong to the range: [-1e7, 1e7].

分析

一开始我是想用两个for循环做的,后来发现漏了各种边界情况,提交数次都无法ac,深感无力。后来0看了讨论区(https://discuss.leetcode.com/topic/81702/o-n-concise-solution-c )的解法恍然大悟:用一个unordered_map即可解决!

用unordered_map<int,int>,key 值保存数组元素,value保存该元素个数。

因此只需遍历这个map,判断这个map里是否存在键值加上k后的键值即可。

唯一需要考虑的是k=0的情况,因为k=0时只有两个相等的元素才能满足。并且根据题意,即使有n对匹配元素(val1,val2)是k匹配的,也只算做一对。因此k=0时,只需要判断这个元素的个数即可,有两个及以上便将个数加1.

代码如下:

class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if(k < 0)return 0;
int k_diff = 0;
unordered_map<int,int>um;
for(int i = 0; i != nums.size(); ++i)
++um[nums[i]];
if(k != 0){
for(auto it = um.begin(); it != um.end(); ++it)
if(um.find(it->first + k) != um.end())
++k_diff;
}else{
for(auto it = um.begin(); it != um.end(); ++it)
if(it->second > 1)
++k_diff;
}
return k_diff;
}
};

心得

写个心得。

unordered_map真心好用啊,很多操作的复杂度也低,在大多数情况下简直是上上之选,以后解题的时候可以优先考虑用unordered_map!

leetcode解题报告(13):K-diff Pairs in an Array的更多相关文章

  1. LeetCode解题报告—— Swap Nodes in Pairs & Divide Two Integers & Next Permutation

    1. Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. For e ...

  2. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  3. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  4. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  5. LeetCode解题报告汇总! All in One!

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 把自己刷过的所有题目做一个整理,并且用简洁的语言概括了一下思路,汇总成了一个表格. 题目 ...

  6. [LeetCode解题报告] 502. IPO

    题目描述 假设 LeetCode 即将开始其 IPO.为了以更高的价格将股票卖给风险投资公司,LeetCode希望在 IPO 之前开展一些项目以增加其资本. 由于资源有限,它只能在 IPO 之前完成最 ...

  7. LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结

    前言: 这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题.该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sor ...

  8. [LeetCode解题报告] 703. 数据流中的第K大元素

    题目描述 设计一个找到数据流中第K大元素的类(class).注意是排序后的第K大元素,不是第K个不同的元素. 你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包 ...

  9. leetCode解题报告5道题(六)

    题目一: Longest Substring Without Repeating Characters Given a string, find the length of the longest s ...

随机推荐

  1. QLineEdit的信号函数

    QLineEdit一共有6个信号函数,并不多,很好理解. ·void cursorPositionChanged( intold, intnew ) 当鼠标移动时发出此信号,old为先前的位置,new ...

  2. golang跨平台编译

    // 目标平台linux 64 SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build //目标平台windows SET CGO_ENA ...

  3. ajax post上传数据时,前端出现的跨域权限问题:ccess to XMLHttpRequest at ‘’rom origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok st

    本人前端使用多个框架时,jq  ajax传参出现如下报错: 最后发现,可能是xhr的相关默认参数被修改了.顾使用jq 传参时,一直报错,jq  ajax额外添加的关键参数: crossDomain: ...

  4. java 框架-分布式服务框架1ZooKeeper

    https://www.cnblogs.com/felixzh/p/5869212.html Zookeeper的功能以及工作原理   1.ZooKeeper是什么?ZooKeeper是一个分布式的, ...

  5. win10下PLSQL Developer 连接ubuntu上安装的oracle 11g

    说明:过程记录的不是很相信,只记录基本步骤.并不适合想一步一步照做的同学. win10下需要的操作 1.微软官网下载instantclient,然后接到到本地一个文件夹,注意路径不要又空格,中文和括号 ...

  6. ztree在onCheck()方法中防止因触发联动关系导致页面多次渲染而卡死的问题

    这几天在项目中遇到了要使用树形选择框, 而且要求比较复杂,具体叙述如下: 首先是有个选择框,左边选择是适用的商品,右边显示已经选择的商品.也就是说,左边每次勾选操作,都要触发一个事件去刷新右边的页面, ...

  7. js检测是不是数字

    function isValueNumber(value) { var reg = (/(^-?[0-9]+\.{1}\d+$)|(^-?[1-9][0-9]*$)|(^-?0{1}$)/); var ...

  8. ARC模式下获取retainCount的方法

    _objc_rootRetainCount(obj)可以获取obj的retainCount,不过不清楚是不是私有api,因此建议调试时使用.

  9. sql语句开启事务

    以下为示例代码: begin tran update 表 where 姓名='A' update 表 where 姓名='B' rollback else commit

  10. Ubuntu18.0 解决python虚拟环境中不同用户下或者python多版本环境中指定虚拟环境的使用问题

    一. 不同用户下配置virtualenvwrapper的问题 问题描述: 安装virtualnev和virtualnevwrapper之后,在.bashrc进行virtualenvwrapper的相关 ...