Leetcode 1375. 灯泡开关 III

这道题比较特殊,直接模拟,时间复杂度在O(N^2)以上

如果灯要想全部变蓝,那么他的index之和一定是(n+1)*n/2, 所以有了如下做法:

class Solution {
public:
    int numTimesAllBlue(vector<int>& light) {
        int ans=0;
        long long sum=0,cnt=0;
        for(auto v : light)
        {
            ++cnt;
            sum+=v;
            if(sum==(cnt+1)*cnt/2)++ans;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/108403059