【Leetcode】1426. Counting Elements

題目地址:

https://leetcode.com/problems/counting-elements/

給定一個數組,數一下有多少個數滿足其加一後也存在於數組中。用哈希表存一下即可。代碼如下:

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public int countElements(int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int n : arr) {
            set.add(n);
        }
    
        int res = 0;
        for (int n : arr) {
            res += set.contains(n + 1) ? 1 : 0;
        }
        
        return res;
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章