Concise C++ solution, use set instead of map


  • 16
    H

    There is really no need to use map, the required length is at least 2, so we just need to insert the mod one iteration later.

    class Solution {
    public:
        bool checkSubarraySum(vector<int>& nums, int k) {
            int n = nums.size(), sum = 0, pre = 0;
            unordered_set<int> modk;
            for (int i = 0; i < n; ++i) {
                sum += nums[i];
                int mod = k == 0 ? sum : sum % k;
                if (modk.count(mod)) return true;
                modk.insert(pre);
                pre = mod;
            }
            return false;
        }
    };

  • 0
    A
    This post is deleted!

  • 2

    By using

    modk.find(mod) != modk.end()
    

    instead of

    modk.count(mod)
    

    it runs faster


  • 0
    E

    wonderful thanks for your answer


  • 0
    Y

    @carterbao

    modk.find won't be faster than modk.count.

    This is a HashSet, every key is unique.

    I think count() is better here because it is shorter.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.