Brain teaser

292  Nim Game   

You can always win a Nim game if the number of stones n in the pile is not divisible by 44.







Second Time 
=============================================


319 Bulb Switcher (N)

A light will be toggled only during the round of its factors, e.g. number 6 light will be toggled at 1,2,3,6 and light 12 will be toggled at 1,2,3,4,6,12. The final state of a light is on and off only depends on if the number of its factor is odd or even. If odd, the light is on and if even the light is off. The number of one number’s factor is odd if and only if it is a perfect square!
So we will only need to loop to find all the perfect squares that are smaller than n!
Actually, the number of perfect square number within n is sqrt(n)



777  Swap Adjacent in LR String  

题目要求根据给定的规则,判断能否从 start string 变换到 end string 。
给出了两种变换的规则,从“XL”到“LX”和从“RX”到“XR”。所以我们可以给出两条规律:
  • 如果start能变换到end,那么除去两个字符串中的"X",剩余的字符串一定相同。因为任意"R""L"的相对顺序都不会发生变化,我们定义出去"X"的字符串为有效字符串
  • 根据变换的规则,"L"不能向右移,“R”不能向左移,所以 start 中“L”对应的 index "i" 一定不小于 end 中 “L”对应的index "j";start 中“R”对应的 index "i" 一定不大于 end 中 “R”对应的index "j"
    1. i >= j, 如果 start[i]==end[j]==”L”
    2. i <= j, 如果 start[i]==end[j]==”R”

    Rule 2 (version 2)
      We must make sure that we have less or equal number of L seen in start than in end and
       less or equal number of R seen in end than in start so that it is possible that after
       shifting L left and R right we can transform start to end.
    Use count sl,el,sr,er while traversing start and end, make sure it always obey (sl <= el && sr >= er)

Comments

Popular posts from this blog

zhitongguigu

Array Part2

Two pointers (Part 1)