Lowest Common Ancestor of a Binary Search 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL)
return NULL;
if(root==p || root==q)
return root;
if(root->left==p && root->right==q || root->left==q && root->right==p)
return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left==NULL)
return right;
if(right==NULL)
return left;
return root;
}
};
Delete Node in a Linked List
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
Valid Anagram
"""哈希表
O(n), O(1)
另外可以只使用一个hash表
"""
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()!=t.size())
return false;
unordered_map<char,int> map;
for(int i=0; i<s.size();i++)
if(map.find(s[i])==map.end())
map.insert({s[i],1});
else
map[s[i]] += 1;
unordered_map<char,int> map2;
for(int i=0; i<t.size();i++)
if(map2.find(t[i])==map2.end())
map2.insert({t[i],1});
else
map2[t[i]] += 1;
auto i = map.begin();
while(i!=map.end()){
if(map2.find(i->first)==map2.end())
return false;
if(map2[i->first]!=i->second)
return false;
i++;
}
return true;
}
};
Binary Tree Paths
"""
"""
class Solution {
public:
void paths(TreeNode* root, string s, vector<string> & v){
if(root!=NULL){
if(s=="")
s += to_string(root->val);
else{
s += "->";
s += to_string(root->val);
}
if(root->left==NULL && root->right==NULL)
v.push_back(s);
paths(root->left, s, v);
paths(root->right, s, v);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> v;
paths(root, "", v);
return v;
}
};
Add Digits
"""O(1)解利用了数学性质,不知道的话挺难做到的。我们写个O(log(n))的。
"""
class Solution {
public:
int addDigits(int num) {
if(num<10)
return num;
int re = 0;
while(num){
re += num%10;
num /= 10;
}
return addDigits(re);
}
};
Ugly Number
"""
"""
class Solution {
public:
bool isUgly(int num) {
if(num == 0)
return false;
while(num%2 == 0)
num /= 2;
while(num%3 == 0)
num /= 3;
while(num%5 == 0)
num /= 5;
if(num == 1)
return true;
return false;
}
};
Missing Number
"""等差数列,简单。 xor的方法也很有趣。
"""
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int sum = (1+n)*n/2;
for(int i=0; i<nums.size(); i++)
sum -= nums[i];
return sum;
}
};
First Bad Version
"""overflow大坑
"""
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int binary_search(int left, int right){
if(left == right-1)
return right;
int mid = left+(right-left)/2;
if(isBadVersion(mid))
return binary_search(left, mid);
else
return binary_search(mid, right);
}
int firstBadVersion(int n) {
return binary_search(0, n);
}
};
Move Zeroes
"""O(n), O(1)
注意j始终单调递增!
"""
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j=0;
for(int i=0; i<nums.size(); i++){
if(nums[i]==0){
for(j=max(j,i+1);j<nums.size();j++){
if(nums[j]!=0){
nums[i] = nums[j];
nums[j] = 0;
break;
}
}
}
}
}
};
Word Pattern
"""两个hash。
O(n)
"""
class Solution {
public:
bool wordPattern(string pattern, string str) {
istringstream iss(str);
vector<string> tokens{istream_iterator<string>{iss},
istream_iterator<string>{}};
if(pattern.size()!=tokens.size())
return false;
unordered_map<char,string> map;
for(int i=0; i<pattern.size(); i++){
if(map.find(pattern[i])==map.end()){
map.insert({pattern[i],tokens[i]});
}
else{
if(map[pattern[i]]!=tokens[i])
return false;
}
}
unordered_map<string,char> map2;
for(int i=0; i<tokens.size(); i++){
if(map2.find(tokens[i])==map2.end()){
map2.insert({tokens[i],pattern[i]});
}
else{
if(map2[tokens[i]]!=pattern[i])
return false;
}
}
return true;
}
};
Nim Game
"""直接递归超时!数学题?。。唉,年龄大了智商捉急,搞奥数那会多牛逼
"""
class Solution {
public:
bool canWinNim(int n) {
if(n%4==0)
return false;
return true;
}
};
Range Sum Query - Immutable
"""空间换时间
"""
class NumArray {
public:
vector<int> memo = {0};
NumArray(vector<int> nums) {
int summ = 0;
for (int n : nums) {
summ += n;
memo.push_back(summ);
}
}
int sumRange(int i, int j) {
return memo[j+1] - memo[i];
}
};
Power of Three
"""蛋疼
"""
class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && 1162261467 % n == 0;
}
};
Power of Four
"""考虑2**k % 3。
当k=2m,2**k=4**m=(1+3)**m,二项式展开(又是高中知识),上述余数为1;
当k=2m+1,2**k=2*4**m=2*(1+3)**m,余数不是1。
"""
class Solution {
public:
bool isPowerOfFour(int num) {
if (num <= 0) return false;
if (num & num - 1) return false; //2的幂,依据二级制的位运算
return num % 3 == 1;
}
};
Reverse String
"""
"""
class Solution {
public:
string reverseString(string s) {
if(s=="")
return s;
int n = s.size()-1;
char temp;
for(int i=0; i<s.size()/2; i++){
temp = s[i];
s[i] = s[n-i];
s[n-i] = temp;
}
return s;
}
};
本文集解答了多个经典的算法题目,包括二叉搜索树的最近公共祖先、链表中删除节点、有效字母异位词判断、二叉树路径、数字相加、丑数判断、缺失数字查找、第一个错误版本定位、零元素移动、单词模式匹配、Nim游戏胜负判断、区间求和、三的幂次判断、四的幂次判断、字符串反转等。
1476

被折叠的 条评论
为什么被折叠?



