Counting Elements Solutions in C++
Number 1426
Difficulty Easy
Acceptance 58.8%
Link LeetCode
Other languages —
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/counting-elements//// Author : liuyubobobo/// Time : 2020-05-02#include <iostream>#include <vector>#include <unordered_set>using namespace std;/// Brute Force/// Time Complexity: O(n^2)/// Space Complexity: O(1)class Solution {public:int countElements(vector<int>& arr) {int res = 0;for(int e: arr)if(find(arr.begin(), arr.end(), e + 1) != arr.end())res ++;return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/counting-elements//// Author : liuyubobobo/// Time : 2020-05-02#include <iostream>#include <vector>#include <unordered_set>using namespace std;/// Sorting and Binary Search/// Time Complexity: O(nlogn)/// Space Complexity: O(1)class Solution {public:int countElements(vector<int>& arr) {sort(arr.begin(), arr.end());int res = 0;for(int e: arr){vector<int>::iterator iter = lower_bound(arr.begin(), arr.end(), e + 1);if(iter != arr.end() && *iter == e + 1)res ++;}return res;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/counting-elements//// Author : liuyubobobo/// Time : 2020-05-02#include <iostream>#include <vector>#include <unordered_set>using namespace std;/// Using HashSet/// Time Complexity: O(n)/// Space Complexity: O(n)class Solution {public:int countElements(vector<int>& arr) {unordered_set<int> set;for(int e: arr) set.insert(e);int res = 0;for(int e: arr) if(set.count(e + 1)) res ++;return res;}};int main() {return 0;}