347. Top K Frequent Elements
Quick Select
快速排序,每次只排一半
T(n) : (1) Explore - LeetCode
b = 2, d=1,a=1
T(n) = T(n/2) + f(n)=T(n/2)+T(n)

那么T(n) 为 O(n)
1 | class Solution { |
review
1 | class Solution { |
快速排序,每次只排一半
T(n) : (1) Explore - LeetCode
b = 2, d=1,a=1
T(n) = T(n/2) + f(n)=T(n/2)+T(n)
那么T(n) 为 O(n)
1 | class Solution { |
review
1 | class Solution { |
1 | class Solution { |
参考236. Lowest Common Ancestor of a Binary Tree
但因为这题是BST,所以有别的方法
以下情况:
1 | /** |
1 | /** |
1 | class Solution { |
写法二
1 | class Solution { |
如果没题目限制使用递归
1 | class Solution { |
1 | class Solution { |
1 | /** |
1 | /** |
两个条件
最大值减去最小值<5
没有重复的数字
1 | class Solution { |
法2
1 | class Solution { |
1 | class Solution { |
稍微优化一下 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
26
27
28
29
30class Solution {
public:
int strToInt(string str) {
int start = 0;
while(str[start] == ' ')
++start;
bool positive = true;
if(str[start] == '+' || str[start] == '-')
positive = str[start++] == '+' ? true : false;
int ret = 0;;
for(int i = start; i < str.size(); ++i)
{
int num = str[i] - '0';
if(isValid(str[i]))
{
if(ret > 214748364 || (ret == 214748364 && num > 7)) // 即使当num == 8时,如果是负数,虽然没越界,但是假设他越界了,依旧可以返回正确的值
return positive ? INT_MAX : INT_MIN;
ret = ret * 10 + num;
}
else
break;
}
return positive ? ret : -ret;
}
private:
bool isValid(char ch)
{
return ch >= '0' && ch <= '9';
}
};