66 plus one
检测数字9,置初始位为1,pushback 0
bug:
1 Line 3: execution reached the end of a value-returning function without returning a value
2 for 循环中 是 i or n iterator
3 Line 11: return-statement with no value, in function returning 'std::vector
121 Best Time to Buy and Sell Stock (time exceeded)
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
思路:一个for 遍历 result > max_profit则赋值,找arr min 并赋值
122. Best Time to Buy and Sell Stock II (ac)
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:把前后相减>0的价格都加起来
169. Majority Element
bug:
Line 11: cannot convert 'std::vector
思路:>>1 = /2
Hash Table
The hash-table solution is very straightforward. We maintain a mapping from each element to its number of appearances. While constructing the mapping, we update the majority element based on the max number of appearances we have seen. Notice that we do not need to construct the full mapping when we see that an element has appeared more than n / 2
times.
sorting
Since the majority element appears more than n / 2
times, the n / 2
-th element in the sorted nums
must be the majority element. This can be proved intuitively. Note that the majority element will take more than n / 2
positions in the sorted nums
(cover more than half of nums
). If the first of it appears in the 0
-th position, it will also appear in the n / 2
-th position to cover more than half of nums
. It is similar if the last of it appears in the n - 1
-th position. These two cases are that the contiguous chunk of the majority element is to the leftmost and the rightmost in nums
. For other cases (imagine the chunk moves between the left and the right end), it must also appear in the n / 2
-th position.
Randomization
This is a really nice idea and works pretty well (16ms running time on the OJ, almost fastest among the C++ solutions). The proof is already given in the suggested solutions.
The code is as follows, randomly pick an element and see if it is the majority one.
Divide and Conquer
This idea is very algorithmic. However, the implementation of it requires some careful thought about the base cases of the recursion. The base case is that when the array has only one element, then it is the majority one. This solution takes 24ms.
Moore Voting Algorithm
Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element.In second phase we need to check if the candidate is really a majority element. Second phase is simple and can be easily done in O(n). We just need to check if count of the candidate element is greater than n/2.
53. Maximum Subarray
思路
单for - compare 每次相加结果与输出结果大小,相加结果与0比较
283. Move Zeroes
219. Contains Duplicate II
思路: hash table—— 存index 为 value, 内容为key
myMap[nums[i]]
solu2:unordered_set
solu3: 用myMap.find && < k
242. Valid Anagram
思路: hash table对同一个字母在不同string 下 ++--;最后数 auto count : counts,若字母次数不为0 则false
solu2(best): 初始化 arr[26] = {0}; arr[s[i] - 'a']++; arr[t[i] - 'a']--;
349. Intersection of Two Arrays
思路: unordered set 找到一个interaction就把原arr中的数字erase掉。
205. Isomorphic Strings
思路:数组中arr['a'] = 1
设置两个arr,初始化-1
每个字母存入index
判断的依据为字母index的数值不同,return false
204. Count Primes
思路:设n个bool vector true,
两个for, 第一个for 从2开始到最后,
第二个for判别语句为 j * i 输出有多少个true (不用查even number) thinking: find how many 1 totally find how many nearby 1 output 4 * the number of 1 - 2 * repeat bugs:1、 return-statement with a value, in function returning 'void' [-fpermissive] thinking: 2 pointers, tenary operater nums1[tar--] = a>=0 && nums1[a] > nums2[b] ? nums1[a--] : nums2[b--]; bugs: no matching function for call to 'std::vector cuz: erase needs iterator instead of index But your code looks buggy on two counts: Take care not to increment You'll also need to adjust 思路: nums[i - count] = nums[i] 118. Pascal's Triangle 思路:Pascal[i].resize(i+1); 思路:const1首相加末相之和,const2数组内元素之和,return差 solution1: 2 pointer, i,j while loop, while sum is greater than target, j--, otherwise i++ solution2: binary search: if(numbers.empty()) return {}; bug: vector.pop_back 不能赋值,vector.back 可以 my solution: pop_back and insert at the front the other solution: https://leetcode.com/problems/rotate-array/discuss/54277/Summary-of-C++-solutions 思路:First iteration to negate values at position whose equal to values appear in array. Second iteration to collect all position whose value is positive, which are the missing values. Complexity is O(n) Time and O(1) space. 思路: maxDepth(root -> left or right) 思路:invertTree(root -> left and right) BFS: inital queue, push root, if root left != null, push,..... do swap left and right 思路:recursive, t1 -> val += t2 -> val; t1 -> left = mergeTrees(t1 -> left, t2 -> left) BFS: inital stack, node1 -> val += node2 -> val; 思路: recursive, isSameTree(p -> left, q -> left) stack: if it is null, dont push into stack 235. Lowest Common Ancestor of a Binary Search Tree 思路: 110. Balanced Binary Tree bugs: Line 17: member access within null pointer of type 'struct TreeNode'( 边界问题没有设置对) 思路:计算左右child的深度,然后比较长度, solution2: 2.The second method is based on DFS. Instead of calling depth() explicitly for each child node, we return the height of the current node in DFS recursion. When the sub tree of the current node (inclusive) is balanced, the function dfsHeight() returns a non-negative value as the height. Otherwise -1 is returned. According to the leftHeight and rightHeight of the two children, the parent node could check if the sub tree In this bottom up approach, each node in the tree only need to be accessed once. Thus the time complexity is O(N), better than the first solution. 108. Convert Sorted Array to Binary Search Tree bugs: invalid conversion from 'TreeNode*' to 'int' [-fpermissive] (Cuz TreeNode *root = new TreeNode(nums[middle]); root is a pointer) 思路: recursive recursive: bool function, check function value when return 669. Trim a Binary Search Tree If the root value in the range [L, R] recursive (iterative !AC) 257. Binary Tree Paths recursive: ; path + to_string(val) iterative: vector<string> res; 基本思路与找max depth 类似,但是会忽略单边为nulll的情况 用BFS DFS Inorder Traversal: Preorder Traversal: Postorder Traversal: Logic goes something like this: Pick a character at i=0th location and compare it with the character at that location in every string. If anyone doesn’t have that just return “” Else append that character in to the result. Increment i and do steps 1-3 till the length of that string. return result 后一个字母大于前一个字母 sum-- else sum++ 67. Add Binary bugs: 边界问题没有处理好 思路: 先匹配needle 和 haystack第一字符的位置,后用substr 取出haystack的字符来比较 substr(起始位置,长度) two pointers, 当不是空格时,移j到空格处后,reverse字符串。 bug: 字符比较只能用' '即 char unordered_map - ++map[magazine[i]]; if (--map[str] < 0) return false; fibonacci numbers take the initial as 1 and 2 463. Island Perimeter
88. Merge Sorted Array
26. Remove Duplicates from Sorted Array
erase
takes an iterator, not an index value. A simple fix is to use docel.erase(docel.begin() + j);
j
if you erase the (j)th element though: you'll skip over values.n
if the number of elements in docel
is reduce27. Remove Element
268. Missing Number
167. Two Sum II - Input array is sorted
for(int i=0; i
int start=i+1, end=numbers.size()-1, gap=target-numbers[i];
while(start <= end) {
int m = start+(end-start)/2;
if(numbers[m] == gap) return {i+1,m+1};
else if(numbers[m] > gap) end=m-1;
else start=m+1;
}189. Rotate Array
448. Find All Numbers Disappeared in an Array
104. Maximum Depth of Binary Tree
226. Invert Binary Tree
617. Merge Two Binary Trees
if (node1 -> left == NULL && node2 -> left != NULL) {
node1 -> left = node2 -> left;
} else if (node1 -> left != NULL && node2 -> left != NULL) {
s1.push(node1 -> left);
s2.push(node2 -> left);100. Same Tree
is balanced, and decides its return value.class solution {
public:
int dfsHeight (TreeNode *root) { if (root == NULL) return 0; int leftHeight = dfsHeight (root -> left); if (leftHeight == -1) return -1; int rightHeight = dfsHeight (root -> right); if (rightHeight == -1) return -1; if (abs(leftHeight - rightHeight) > 1) return -1; return max (leftHeight, rightHeight) + 1; } bool isBalanced(TreeNode *root) { return dfsHeight (root) != -1; } };
101. Symmetric Tree
we need return the root, but trim its left and right subtree;
else if the root value < L
because of binary search tree property, the root and the left subtree are not in range;
we need return trimmed right subtree.
else
similarly we need return trimmed left subtree.112. Path Sum
if (root == NULL) return res;
stack
stack<string> pathStack;
s.push(root);
pathStack.push(to_string(root->val));
while (!s.empty()) {
TreeNode * curNode = s.top(); s.pop();
string tmpPath = pathStack.top(); pathStack.pop();
if (curNode->left == NULL && curNode->right == NULL) {
res.push_back(tmpPath); continue;
}
if (curNode->left != NULL) {
s.push(curNode->left);
pathStack.push(tmpPath + "->" + to_string(curNode->left->val));
}
if (curNode->right != NULL) {
s.push(curNode->right);
pathStack.push(tmpPath + "->" + to_string(curNode->right->val));
}
}
return res;107. Binary Tree Level Order Traversal II
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2. Visit the root.
3. Traverse the right subtree, i.e., call Inorder(right-subtree)
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
BFS
Level order traversal of a tree is breadth first traversal for the tree.
res[level].push_back(root -> val);
BFS(res, root -> left, level + 1);
BFS(res, root -> right, level + 1);
string14. Longest Common Prefix
344. Reverse String
two pointers- swap13. Roman to Integer
a[i] - '0'
while carry == 1
string and char的区别
carry 先加a 再 加 b28. Implement strStr()
557. Reverse Words in a String III
383. Ransom Note
70. Climbing Stairs