532. 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 = 2Output: 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 = 1Output: 4Explanation: 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 = 0Output: 1Explanation: 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].
去重第一步,看是否可以转化为不重复的情况,两个数相差K,想要将这两个数保存到map,其实只要找x + k存在就可以了。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
if (k < 0) return 0;
unordered_map<int, int> map;
for (int num : nums) map[num]++;
int res = 0;
for (auto m : map) {
if (map.find(m.first + k) != map.end()) {
if (k == 0 && map[m.first + k] == 1)
continue;
res++;
}
}
return res;
}
};
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 \ 3 / 2Output:1Explanation:The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
此题主要的问题是,前继节点如何保存的问题,此题明确给出是正整数,所以可以使用初始值为-1,如果没有给出是正数,那么只能使用指针来保存pre,指针的初始值是Nullptr,考虑到内存释放问题,可以使用智能指针。
class Solution {
void inorder(TreeNode* root, int& res, shared_ptr<int>& tmp) {
if (!root) return;
inorder(root->left, res, tmp);
if (tmp == nullptr) {
tmp = shared_ptr<int>(new int(root->val));
}
else {
res = min(res, abs(*tmp - root->val));
*tmp = root->val;
}
inorder(root->right, res, tmp);
}
public:
int getMinimumDifference(TreeNode* root) {
int res = INT_MAX;
shared_ptr<int> tmp = nullptr;
inorder(root, res, tmp);
return res;
}
};