Sunday, September 14, 2014

Merge Intervals - LeetCode

Merge Intervals


1. sort Intervals
2. compare last interval in result with current Interval.

Two Sum - LeetCode

Two Sum

Using HashMap to solve this problem would be much easier.


String to Integer (atoi) - LeetCode

String to Integer (atoi)

Watch out the corner cases. 

Climbing Stairs - LeetCode

Climbing Stairs

1. Recursive:
We can use recursive way to solve this problem: O(n) = O(n - 1) + O(n - 2).

2. DP:
This method also very straightforward. dp[i] means how many ways to reach level i. So it would take O(n) time and O(n) space to solve the problem.

3. Two pointers:
We also can use to pointers to store the info. It is like DP. But the space is reduced to O(1).


Monday, September 8, 2014

Validate Binary Search Tree - LeetCode

Validate Binary Search Tree

This problem is like the other tree questions, recursive method is the easiest read way.

Here is the code:


Pow(x, n) - LeetCode

Pow(x, n)

This question is very easy. But the corner case must be considered in.

1. negative n.
2. n equals to 0.

Then we can using recursive method to solve this problem.

Here is the code: 
Additional throughout: how about n is also double?

Word Ladder - LeetCode

Word Ladder


For this problem, BFS is better than DFS. 

DFS, it's like from the first char to the last char of the word, try to match the dictionary. However, if there is not match, then start from last matching char and do the same again. So it is not efficiency. 

Using BFS, it is like Level traverse a tree. So it would reduce the times for matching. 

Here is the code. Using two queue( the distance Queue is not required. it just used for store the distance every time generate.) to do the BFS. (when mention the BFS, the first thought must be Queue. LOL).