Kth Smallest Element in a BST
题意:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
Hint:
Try to utilize the property of a BST.
What if you could modify the BST node's structure?
The optimal runtime complexity is O(height of BST).
思路:
在一个 BST 中找第 k 小的数,而且利用 BST 的性质来做。找第 k 小什么时候最方便呢?如果数组是有序的那遍历到第 k 个就好了。
BST 可不可以变成一个有序的数组呢?或者说,什么时候我们会从 BST 中得到一组有序的数呢?由 BST 左子树的值都小于根节点,右子树的值都大于根节点。所以中序遍历的时候得到的就是有序数组。那么,只要中序遍历到第 k 个输出就好了。
代码:
/**
* 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:
int kthSmallest(TreeNode* root, int k) {
int cur = 0;
/* 非递归中序遍历 */
stack<TreeNode*> s;
TreeNode* p = root;
while(p != NULL || !s.empty()) {
while(p != NULL) {
s.push(p);
p = p->left;
}
if(!s.empty()) {
p = s.top();
s.pop();
cur++;
/* 第 K 个 */
if(cur == k) return p->val;
p = p->right;
}
}
}
};
Delete Node in a Linked List
题意:
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
思路:
删除给定的节点。用下个节点的值代替当前节点,并释放下个节点空间。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* next = node->next;
*(node) = *(node->next);
delete next;
}
};
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 lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
思路:
在二叉搜索树上寻找两个节点的最近公共祖先。利用二叉搜索树的性质,用 p 和 q 的值与根节点的比较结果决定最近公共祖先的位置。
代码:
/**
* 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) {
TreeNode* t;
/* 让 p 比 q 小 */
if (p->val > q->val) {
t = p;
p = q;
q = t;
}
/* p 和 q 在根节点两侧,或者 p 和 q 某一个等于根节点,根节点就是最近公共祖先 */
if (p->val <= root->val && q->val >= root->val)
{
return root;
}
if(p->val < root->val && q->val < root->val)
{
/* p 和 q 都在根节点左侧,最近公共祖先肯定在左侧 */
return lowestCommonAncestor(root->left, p, q);
} else {
/* p 和 q 都在根节点右侧,最近公共祖先肯定在右侧 */
return lowestCommonAncestor(root->right, p, q);
}
}
};
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.
Note:
You may assume the string contains only lowercase alphabets.
思路:
一个单词是否可以由另一个单词重组而成。首先两个单词的长度要一样,其次包含每个字母的个数要一样。我的想法就是直接使用 map 统计字母的个数就好了。
代码:
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
map<char,int> letter;
for(int i = 0;i < s.size(); i++) {
letter[s[i]] ++;
}
for(int j = 0;j < t.size(); j++) {
if( --letter[t[j]] < 0) {
return false;
}
}
return true;
}
};
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?
思路:
没有最后的要求的话,肯定是循环+递归,done。可是 O(1) 啊...有种直觉肯定是数学规律了...然而没有想出来...
真正的 Wiki 在这:https://en.wikipedia.org/wiki/Digital_root 叫做 digital root. 规律为:
也可以概括为:
其实用了同余的性质:
代码:
递归的:
class Solution {
public:
int addDigits(int num) {
int ans = 0;
do {
ans += num % 10;
num /= 10;
} while (num);
if(ans / 10) return addDigits(ans);
else return ans;
}
};
无递归的:
class Solution {
public:
int addDigits(int num) {
return 1 + ((num-1)%9);
}
};