Just share O(n) time O(1) space solution


  • 2

    See all is O(1) solution, just spent a little time to figure out how to get value in one pass. Happy to share it.

    public class Solution {
        public int bulbSwitch(int n) {
            if (n == 0) return 0;
            int i = 1;
            int prev = 0, cur = 0, multi = 1;
            while (i <= n) {
                while (i < multi * multi && i <= n) {
                    cur = prev;
                    i++;
                }
                if (i++ <= n) cur = prev + 1;
                prev = cur;
                multi++;
            }
            return cur;
        }
    }
    

Log in to reply
 

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