水题
104. Maximum Depth of Binary Tree
题意:求给定根节点对应的二叉树的最大深度。
求解思路:直接dfs遍历即可,对每个节点dfs时:dfs遍历完以当前节点为根节点的子树后更新该子树的最大深度,时间复杂度为
O(n)
,
n
为节点数。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
class Solution {
public:
int maxDepth(TreeNode* root) {
return cal_depth(root);
}
int cal_depth(TreeNode* &root) {
if (root == NULL) return 0;
return max(cal_depth(root -> left), cal_depth(root -> right)) + 1;
}
};
389. Find the Difference
题意:给定两个字符串,分别为s和t,t为组成s的字母中随机再重组,在此前提下,再在任意某一位置添加一个字母,找出这个字母。
求解思路:直接统计s和t中每个字母的出现次数,找不同即可,时间复杂度为
class Solution {
public:
char findTheDifference(string s, string t) {
int cnt_a[26], cnt_b[26];
for (int i = 0; i < 26; i++) cnt_a[i] = cnt_b[i] = 0;
for (int i = 0; i < s.length(); i++) cnt_a[s[i] - 'a']++;
for (int i = 0; i < t.length(); i++) cnt_b[t[i] - 'a']++;
int ii;
for (int i = 0; i < 26; i++)
if (cnt_a[i] != cnt_b[i]) {
ii = i; break;
}
return char('a' + ii);
}
};
387. First Unique Character in a String
题意:给定一个字符串,找出里面第一个只出现了一次的那个字符,如果没有则返回
−1
。
求解思路:直接统计这个字符串每个字符的出现次数,再根据这个数组去顺序遍历原字符串的每个字符,即可找到在原字符串中只出现了一次的字符的下标,时间复杂度为
O(n)
,
n
为字符串的长度。
class Solution {
public:
int firstUniqChar(string s) {
int cnt[26];
for (int i = 0; i < 26; i++) cnt[i] = 0;
for (int i = 0; i < s.length(); i++) cnt[s[i] - 'a']++;
int ans = -1;
for (int i = 0; i < s.length(); i++)
if (cnt[s[i] - 'a'] == 1) {
ans = i; break;
}
return ans;
}
};
383. Ransom Note
题意:给定一个“杂志”字符串a,和另一个字符串b,判断b是否可以由a构造得到,即是否可以选取部分(或全部)a中出现的字符来排列组合得到b。
求解思路:分别统计两个字符串每个字符的出现次数,若存在b中某字符的出现次数大于a中同样这个字符的出现次数则b不可以由a构造得到,否则可以。时间复杂度为
bool canConstruct(char* ransomNote, char* magazine) {
int cnt_a[26], cnt_b[26], i;
for (i = 0; i < 26; i++) cnt_a[i] = cnt_b[i] = 0;
int alen = strlen(ransomNote), blen = strlen(magazine);
for (i = 0; i < alen; i++) cnt_a[ransomNote[i] - 'a']++;
for (i = 0; i < blen; i++) cnt_b[magazine[i] - 'a']++;
for (i = 0; i < alen; i++)
if (cnt_a[ransomNote[i] - 'a'] > cnt_b[ransomNote[i] - 'a']) return 0;
return 1;
}
下次我想弃leetcode去刷codeforces的题目,那个虽然比较难,但是比较有趣 OTZ