4Sum II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l)
there are such that A[i] + B[j] + C[k] + D[l]
is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
Example:
Input: A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] Output: 2
1. 分别计算A,B和C,D的所有可能的和,然后遍历所有可能性。
2. 开始想能不能用2Sum的思想去做。将C和D先进行sort。但是2Sum那道题本身就是排序的,在这道题中进行排序会消耗很多时间。
3. 非常直接的思想是O(n^4),但是数组加和会有重复结果。可以从这个角度去优化
4. 但是就算数组加和没有重复结果。O(n^4)也将数组加和的结果重复计算了很多次,事实上我们并不需要这样。
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
int rst = 0;
unordered_map<int, int> map1;
for (int a : A){
for (int b : B){
int sum = a + b;
if (map1.find(sum) != map1.end()) map1[sum]++;
else map1[sum] = 1;
}
}
for (int c : C){
for (int d : D){
int sum = c + d;
int target = (-1) * sum;
if (map1.find(target) != map1.end())
rst += map1[target];
}
}
return rst;
}
Kth Smallest Element in a BST
解法1:中序遍历。即从小到大遍历整个查找树
bool traverse(TreeNode* root, int k, int& rst, int& count){
if (root == NULL) return false;
bool found = traverse(root->left, k, rst, count);
count++;
if (count == k){ //找到第k小
rst = root->val;
return true;
}
if(!found) found = traverse(root->right, k, rst, count); //如果已经找到,就无需搜索另一边
return found;
}
int kthSmallest(TreeNode* root, int k) {
int rst = 0;
int count = 0;
traverse(root, k, rst, count);
return rst;
}
解法2:快速选择的思想。但是countNodes会有重复计算。使用hashmap来避免重复计算
int kthSmallest(TreeNode* root, int k) {
unordered_map<int,int> small;
return kth(root, k, small);
}
int kth(TreeNode* root, int k, unordered_map<int, int>& small){
int count = countNodes(root->left, small);
if (k <= count) {
return kth(root->left, k, small);
} else if (k > count + 1) {
return kth(root->right, k-1-count, small); // 1 is counted as current node
}
return root->val;
}
int countNodes(TreeNode* root, unordered_map<int, int>& small) {
if (root == NULL) return 0;
if (small.find(root->val) != small.end())
return small[root->val];
int count = 1 + countNodes(root->left, small) + countNodes(root->right, small);
small[root->val] = count;
return count;
}