LeetCode 30 days challenge: Counting Elements

題目名稱 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;    
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章