[LeetCode] Easy Problems
文章目录
Binary Tree Level Order Traversal[102]
1 | vector<vector<int>> levelOrder(TreeNode* root) { |
Isomorphic Strings[205]
- Should have two direction check(one word for key, the other for value and vice versa)
Compare Version Numbers[165]
- Remember this case, “1” = “1.0”
Reverse Integer
- If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100. (handled implicitly by the naive method)
- the reversed integer might overflow?
Solution:
- Method1: Use long int for the reversed int
- Method2: check the number before addition and multiplication
Method11
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25int reverse(int x) {
int flag = 1;
long result = 0;
if(x<0)
{
flag = -1;
x = abs(x);
}
while(x>0)
{
result = result * 10;
if(result<0)
return 0;
result += x % 10;
if(result<0)
return 0;
x = x / 10;
}
if (result>INT_MAX)
return 0;
result = result * flag;
return (int)result;
}
Method2:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26int reverse(int x) {
int flag = 1;
int result = 0;
int d = 0;
if(x<0)
{
flag = -1;
x = abs(x);
}
while(x>0)
{
d = x % 10;
if (result > (INT_MAX-d)/10)
return 0;
result = result * 10;
result += d;
if(result<0)
return 0;
x = x / 10;
}
result = result * flag;
return result;
}
Remove Nth Node From End of List
- List Problems if the naive way is so easy. Think about how to make it use less time and memory. Use a different pointer is always a right way to think about.