leetcode刷題,總結,記錄,備忘 319

2021-07-09 05:10:52 字數 1200 閱讀 1686

leetcode319, bulb switcher

there are n bulbs that are initially off. you first turn on all the bulbs. then, you turn off every second bulb. on the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). for the nth round, you only toggle the last bulb. find how many bulbs are on after n rounds.

example:

given n = 3. 

at first, the three bulbs are [off, off, off].

after first round, the three bulbs are [on, on, on].

after second round, the three bulbs are [on, off, on].

after third round, the three bulbs are [on, off, off].

so you should return 1, because there is only one bulb is on.

subscribe to see which companies asked this question

一開始並沒有弄懂題目的意思,還使用位運算之類,搞了半天,提交了十幾次都沒成功,無奈去諮詢別人的部落格,自己又思考了良久,才弄懂這題,題目的意思是第一輪全亮,第二輪每逢第二個滅掉,第三輪每逢第三個反轉,之後第n輪就反轉第n個燈的狀態。仔細一想,就可以得知,第幾個燈一共被操作幾次,就可以得到其最後的結果,如果是第質數個的燈的話,比如1,3,5,7,11,在整個過程中只會被操作兩次,即第一次和第n次,所以最後的狀態一定是滅的。從此可以看出第n個燈的操作次數是他們的的因數的個數,比如6,因數為1,2,3,6,一共操作了四次,最後結果是滅的,所以只有奇數的操作次數的燈最後才會亮,比如第4個燈,因數為1,2,4,因為存在是2的平方的原因,因數少了乙個,這樣的燈在最後是會亮著的,所以這道題目,就是求<=n的數中,有多少個完全平方數,**就很簡單了。

class solution 

};

leetcode刷題,總結,記錄,備忘 226

leetcode226題。invert binary tree 倒置二叉樹。想不到這題還有個梗,挺有意思的。我一開始自作聰明,想用乙個棧乙個佇列來做,用中序遍歷,把節點push進棧中,把節點的指push進佇列中,遍歷完之後,分別從棧頂和佇列頂拿出節點和數值,賦值。一開始想著感覺還挺對的,遞交了幾次都...

leetcode刷題,總結,記錄,備忘83

leetcode83.for example,given1 1 2,return1 2.given1 1 2 3 3,return1 2 3.不想說什麼了,比較簡單的題目,大爺的我提了6,7遍才過,因為中間有個流程一直疏忽了,如果當前項值域和下乙個結點的值域相同的話,在將下乙個結點刪掉,即連到下乙個...

leetcode刷題,總結,記錄,備忘202

leetcode202 credits special thanks to mithmatt and ts for adding this problem and creating all test cases.還是比較簡單的題目,雖然我提的次數比較多,又拉低了通過率,真是無情。每次計算如果得到結果...