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 = 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].
就是在一个序列中,计算序列中各个元素的差的绝对值,然后找到与目标差的绝对值相等的个数。其中要注意的是相差的值为的一对数不能重复。
代码实现
法一:
直接上暴力破解。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int len = nums.size(), res = 0;
if(k < 0) return res;
sort(nums.begin(), nums.end());
for(int i = 0; i < len; i++) {
if(i > 0 && nums[i] == nums[i-1]) continue;
int d1 = nums[i] - k, d2 = nums[i] + k;
for(int j = i+1; j < len; j++) {
if(j > i+1 && nums[j] == nums[j-1]) continue;
if(nums[j] == d1 || nums[j] == d2) res++;
}
}
return res;
}
};
法二:使用set和map一起协作。
使用map记录出现过的数字,使用set记录一对符合要求的数的更小数。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int len = nums.size(), res = 0;
if(k < 0) return res;
set<int> st;
map<int, int> mp;
for(int i = 0; i < len; i++) {
int d1 = nums[i] + k, d2 = nums[i] - k;
if(mp.count(nums[i]+k)) { st.insert(nums[i]); }
if(mp.count(d2)) { st.insert(d2); }
mp[nums[i]]++;
}
return st.size();
}
};
531. Lonely Pixel I
题目描述
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of ‘B’ and ‘W’, which means black and white pixels respectively.
A black lonely pixel is character ‘B’ that located at a specific position where the same row and same column don’t have any other black pixels.
Example:
Input:
[['W', 'W', 'B'],
['W', 'B', 'W'],
['B', 'W', 'W']]
Output: 3
Explanation: All the three ‘B’s are black lonely pixels.
Note:
The range of width and height of the input 2D array is [1,500].
这道题目就是说如果一个字符B在横纵都是只有一个,那么我们认为结果就是一个lonely的数,然后统计有多少个这样的结果。
代码实现
使用哈希统计横纵的字符B的个数,然后取更小的数值为1的数。
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& pic) {
int m = pic.size(), n = m?pic[0].size():0, res = 0;
if(!m) return 0;
cout << m<< " "<<n<< endl;
vector<int> hash(m+n, 0);
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(pic[i][j] == 'B') {
hash[i]++;
hash[m+j]++;
}
}
}
int cnt1 = 0, cnt2 = 0;
for(int i = 0; i < m; i++)
if(hash[i] == 1) cnt1++;
for(int i = 0; i < n; i++)
if(hash[i+m] == 1) cnt2++;
return min(cnt1, cnt2);
}
};