Leetcode532. 找出数组中绝对值为k的数值对的数目
来源:互联网 发布:陕西网络作家协会 编辑:程序博客网 时间:2024/06/16 05:59
Leetcode532. 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.
Example1:
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.Example2:
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).Example3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
解题分析
题目乍一看,给我的第一思路就是要消除数组中重复的元素;因为题目明确说了,相同的元素只算一次。
接下来我们来考虑怎样统计数组中绝对值为k的数值对的数目。我们可以这样想,用另外一个数组来存储每个元素对应的数值对的值。而我们知道绝对值为k的数字有两个,即k和-k。因此,在前面消除数组重复元素的时候,对数组从小到大进行排序,这样可以只考虑一种情况而减少重复工作。
在遍历数组元素的时候,我们先判断在另一个数组中有没有该数组元素,如果有,说明就找到了一个数值对;然后再把该元素对应的数值对的值(即该元素的值+k)存进数组中。这样当数组遍历完之后,数目的计算就完成了。
但是这里还有一个细节问题容易忽略,就是k=0的情况。前面我们消除了数组的重复元素,因此此时数组中没有任何一个重复元素,如果我们按照上面的做法,最后的结果就始终为0。所以,在消除数组重复元素之前,我们需要用unordered_map哈希表来统计每个元素出现的次数,如果次数大于1,数值对的数目就加1,这样所有的问题就解决了。
源代码
class Solution {public: int findPairs(vector<int>& nums, int k) { int pair = 0, size = nums.size(), i; unordered_map<int, int> map; for (i = 0; i < size; i++) { map[nums[i]]++; } sort(nums.begin(), nums.end()); vector<int>::iterator end_unique = unique(nums.begin(), nums.end()); nums.erase(end_unique, nums.end()); if (k == 0) { for (i = 0; i < nums.size(); i++) { if (map[nums[i]] > 1) { pair++; } } } else if (k > 0) { vector<int> add; for (i = 0; i < nums.size(); i++) { vector<int>::iterator it_add = find(add.begin(), add.end(), nums[i]); if (it_add != add.end()) { pair++; } add.push_back(nums[i] + k); } } return pair; }};
这只是我对这道题的一些想法,有问题还请在评论区讨论留言~
- Leetcode532. 找出数组中绝对值为k的数值对的数目
- 【查找】在按照绝对值排序的数组中,找出和为k的两个数的下标
- 找出数组中第K大的数值
- 找到list中差距为k的数值对
- 找出整数数组中两个数差值的绝对值最小
- 找出整数数组中两个数差值的绝对值最小
- 找出有序数组中绝对值最小的元素
- 找出有序数组中绝对值最小的数
- 找出有序数组中绝对值最小的元素
- 找出数组中缺失的两个数(数组长度为98,数值范围1-100,数值无重复)
- 快速找出数组中元素数目超出一半的元素
- 找出有序数组中的绝对值的最大值
- 找出数组中最小的 K 个数
- Leetcode667. 求一种数组排列方式使数组相邻数值对有k个不同绝对值
- 从一个长度为n的数组中找出前k个最小值的最优实现
- 找出数组a[]中符合a[i]+a[j]=K的数对
- 数值的绝对值
- 取数值的绝对值
- 由某云盘下载速度慢而引发的一场血案!!!
- C#回顾学习笔记二十七:using的两个作用
- 一款多功能的移动端车牌识别软件
- Cordova webapp+android studio开发环境的搭建
- 爬虫入门1——爬图
- Leetcode532. 找出数组中绝对值为k的数值对的数目
- 034、java常用类-Scanner类
- Windows系统如何通过修改注册表启用/禁用任务管理器
- sublimeemmet jsFormat git相关
- hdu6216 A Cubic number and A Cubic Number 打表找规律 + 二分
- esp8266 inet_ntoa函数实现 ip地址转换为字符串 MAC地址转字符串
- Tomcat服务端工程部署遇到的 “The method getDispatcherType() is undefined for the type HttpServletReques
- [有用] WIFI模块ESP8266的使用指南(客户端和服务器两种模式建立)
- xcode升级不能识别设备