Try a blog in Markdown mode.
56 Merge Intervals
Solution:
- O(nlogn) Sort all Intervals
- O(n) Merge them
338 Counting Bits
Solution:
- ‘10011’ in binary system means ‘2^0+2^1+2^4’ in decimal system.
- We can get the number of 1 in ‘10011’ if we know it in ‘0011’, because it is the number of 1 in ‘0011’ plus 1.
- Let f[n] be the number of 1 in number ‘n’. We have f[10011]=f[0011]+1
- Set f[0]=0 first. How to get f[i]?
- Suppose i=2^t+…, then f[i]=f[i-2^t]+1
- For i=2^t, f[i]=1
- Finish it. O(n) for this program
344 Reverse String
Solution:
- O(n)Reverse String
292 Nim Game
Solution:
- return N % 4;
371 Sum of Two Integers
Solution:
- Bitwise operations.
- How to calculate 10011+11010 ?
- No carry propagation,1+1=0; 0+1=1; 0+0=0; Same rule as XOR operation .
- 10011 XOR 11010=01001.
- While in fact 1+1=10; 0+1=01; 0+0=00; for the 1 in high bit, we use AND operation.
- 10011 AND 11010 =10010.
- 10010 << 1=100100.
- Now, if you could calculate 01001+100100 without using ‘+’, you could finish this question.
- Ask me how? No reply.