[LeetCode]532. K-diff Pairs in an Array
2017-06-05 21:41
459 查看
[LeetCode]532. K-diff Pairs in an Array
题目描述
思路
哈希,计数如果k为负,直接返回0
如果k为0,即为求重复元素
代码
#include <iostream> #include <unordered_map> #include <vector> #include <algorithm> using namespace std; class Solution { public: int findPairs(vector<int>& nums, int k) { int res = 0; if (k < 0) return res; unordered_map<int, int> um; for (int num : nums) um[num]++; for (auto p : um) { if (k == 0) { if (p.second > 1) res += 1; } else { if (um.count(p.first + k)) res += 1; } } return res; } }; int main() { vector<int> nums = { 1,2,3,4,5 }; Solution s; cout << s.findPairs(nums, -1) << endl; system("pause"); return 0; }
相关文章推荐
- LeetCode - 532. K-diff Pairs in an Array
- [LeetCode]532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- leetcode 532. K-diff Pairs in an Array 相差为k的元素对
- [leetcode] 532. K-diff Pairs in an Array
- 【leetcode】532. K-diff Pairs in an Array(Python & C++)
- leetcode 532. K-diff Pairs in an Array
- LeetCode532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array (在数组中相差k的配对)
- leetcode 532. K-diff Pairs in an Array
- leetcode532. K-diff Pairs in an Array
- 【LeetCode】532. K-diff Pairs in an Array
- [LeetCode] 532. K-diff Pairs in an Array
- Leetcode 532. K-diff Pairs in an Array
- [Leetcode] 532. K-diff Pairs in an Array 解题报告
- 【leetcode】532. K-diff Pairs in an Array
- [leetcode]: 532. K-diff Pairs in an Array
- LeetCode 532. K-diff Pairs in an Array
- 2017.11.22 LeetCode - 532. K-diff Pairs in an Array【简单二分】