Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree(BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia:“The lowest common ancestor is defined between two nodes v and w as the lowestnode in T that has both v and w as descendants (where we allow anode to be a descendant of itself).
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){
if(root==NULL)
return NULL;
if(root==p||root==q)
return root;
if(p->val<root->val&&q->val>root->val)
return root;
if(p->val>root->val&&q->val<root->val)
return root;
if(p->val>root->val&&q->val>root->val)
return lowestCommonAncestor(root->right,p,q);
if(p->val<root->val&&q->val<root->val)
return lowestCommonAncestor(root->left,p,q);
}
};
递归的使用:①先考虑最简单的情况
②设置递归的下一层
Majority Element
Given an array of size n,find the majority element. The majority element is the element that appearsmore than ⌊
n/2
⌋
times.
You may assume that the array is non-empty and the majorityelement always exist in the array.
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return(nums[nums.size()/2]);
}
};
Contains Duplicate
Given anarray of integers, find if the array contains any duplicates. Your functionshould return true if any value appears at least twice in the array, and itshould return false if every element is distinct.
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(),nums.end());
if(nums.size()<=1)
return false;
for(int i=0;i<nums.size();i++)
if(nums[i]==nums[i+1])
return true;
return false;
}
}
Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s ="anagram", t ="nagaram", return true.
s ="rat", t ="car", return false.
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size()!=t.size())
return false;
int a[26][2]={0};
int i;
for(i=0;i<s.size();i++){
a[t[i]-'a'][0]++;
a[s[i]-'a'][1]++;
}
for(i=0;i<26;i++){
if(a[i][0]!=a[i][1])
return false;}
return true;
}
};
注:这里用到了桶排序的思想,重要思想!!
Excel Sheet Column Number
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return itscorresponding column number.
For example:
A -> 1
B-> 2
C-> 3
...
Z-> 26
AA -> 27
AB -> 28
class Solution {
public:
int titleToNumber(string s) {
int num=0;
int n=0;
for(int i=s.size()-1;i>=0;i--)
{ num=(s[i]-'A'+1)*(pow(26,n))+num;
n++;}
return num;
}
};
Add Digits
Given a non-negative integer num
,repeatedly add all its digits until the result has only one digit.
For example:
Given num= 38
, the process is like: 3+ 8 = 11
, 1+ 1 = 2
. Since 2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
class Solution {
public:
int addDigits(int num) {
if(num<10)
return num;
else return (num-1)%9+1;
}
};
注:这里用到了初等数论的弃九法,即:一个数可以写作 n=(a+b+c+d+e)+(9999*a+999*b+99*c+9*d).,后面一部分用9求余数始终为0,前面部分就是我们所需要的。