题目名称 Counting Elements
题目描述:
Given an integer array arr, count element x such that x + 1 is also in arr.
If there’re duplicates in arr, count them seperately.
例子:
Example 1:
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
Example 2:
Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
Example 3:
Input: arr = [1,3,2,3,5,0]
Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
Example 4:
Input: arr = [1,1,2,2]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.
Constraints:
1 <= arr.length <= 1000
0 <= arr[i] <= 1000
提示
Hide Hint #1
Use hashset to store all elements.
Hide Hint #2
Loop again to count all valid elements.
我的理解
最初的想法就是两层循环,对每一个元素a,找arr数组中是否存在a+1. 时间复杂度大致为o(n^2)。
后来看到了提示,应该用哈希表来解决这个问题,虽然要遍历两次,但是时间复杂度缩减到o(n)。
第一次循环来建立键值对的关系,键为元素实际值,值为元素对应索引。用map数据结构来存储键值信息,对于相同的键,值存储在vector里面。
第二次循环通过遍历map,来查看对于每一个键元素,是否存在键+1的元素。
C++ solution
class Solution {
public:
int countElements(vector<int>& arr) {
map<int,vector<int>> dict;
map<int, vector<int>>::iterator iter;
int cnt = 0;
for(int i = 0; i < arr.size(); i++){
iter = dict.find(arr[i]);
if(iter != dict.end())
dict[arr[i]].push_back(i);
else
dict[arr[i]] = {i};
}
map<int, vector<int>>::iterator iter1;
for(iter = dict.begin(); iter != dict.end(); iter++){
iter1 = dict.find(iter->first + 1);
if(iter1 != dict.end())
cnt += dict[iter->first].size();
}
return cnt;
}
};