-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek7
92 lines (71 loc) · 2 KB
/
week7
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
First Unique Character in a String
class Solution {
public:
int firstUniqChar(string s) {
int a[256] = {0};
for(int i = 0; i < s.length(); i++)
{
a[s[i]]++;
}
for(int i = 0; i < s.length(); i++)
{
if(a[s[i]] == 1)
return i;
}
return -1;
}
};
Symmetric Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isMir(TreeNode* r1, TreeNode* r2)
{
if(r1 == nullptr)
return r2 == nullptr;
if(r2 == nullptr)
return false;
if(r1->val != r2->val) return false;
return isMir(r1->left, r2->right) && isMir(r1->right, r2->left);
}
bool isSymmetric(TreeNode* root) {
if(root == nullptr) return true;
return isMir(root->left, root->right);
}
};
Candy:
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candy (ratings.size(), 1);
int n = ratings.size();
if(ratings[0] > ratings[1] && candy[0] < candy[1])
candy[0] = candy[1] +1;
for(int i = 1; i < n-1; i++)
{
if(ratings[i] > ratings[i-1] && candy[i] <= candy[i-1])
candy[i] = candy[i-1]+1;
}
if(ratings[n-1] > ratings[n-2] && candy[n-1] <= candy[n-2])
candy[n-1] = candy[n-2] +1;
for(int i = n-2; i > 0; i--)
if(ratings[i] > ratings[i+1] && candy[i] <= candy[i+1])
candy[i] = candy[i+1]+1;
if(ratings[0] > ratings[1] && candy[0] <= candy[1])
candy[0] = candy[1] +1;
int sum = 0;
for(int i = 0; i < n; i++)
{
sum += candy[i];
}
return sum;
}
};