leetcode record

66 plus one

检测数字9,置初始位为1,pushback 0

bug:

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<int>' [-fpermissive]

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<int>' to 'int' in return

思路:>>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 <n,把相应vector 位置成false

                          输出有多少个true

          (不用查even number)

463. Island Perimeter

       thinking: find how many 1 totally

                        find how many nearby 1

                       output 4 * the number of 1 - 2 * repeat            

88. Merge Sorted Array

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--];

26. Remove Duplicates from Sorted Array

 bugs: no matching function for call to 'std::vector<int>::erase(int&)'

      cuz: erase needs iterator instead of index

    erase takes an iterator, not an index value. A simple fix is to use docel.erase(docel.begin() + j);

But your code looks buggy on two counts:

  1. Take care not to increment j if you erase the (j)th element though: you'll skip over values.

  2. You'll also need to adjust n if the number of elements in docel is reduce

 

27. Remove Element

思路: nums[i - count] = nums[i]

118. Pascal's Triangle

 思路:Pascal[i].resize(i+1);

268. Missing Number

思路:const1首相加末相之和,const2数组内元素之和,return差

167. Two Sum II - Input array is sorted

solution1: 2 pointer, i,j while loop, while sum is greater than target, j--, otherwise i++

solution2: binary search:    if(numbers.empty()) return {};
    for(int i=0; i<numbers.size()-1; 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

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

448. Find All Numbers Disappeared in an Array

思路: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.

104. Maximum Depth of Binary Tree

思路: maxDepth(root -> left or right)

226. Invert Binary Tree

思路:invertTree(root -> left and right)

BFS: inital queue, push root, if root left != null, push,..... do swap left and right

617. Merge Two Binary Trees

思路:recursive, t1 -> val += t2 -> val; t1 -> left = mergeTrees(t1 -> left, t2 -> left)

 BFS: inital stack,  node1 -> val += node2 -> val;
            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

思路: recursive,  isSameTree(p -> left, q -> left)

stack: if it is null, dont push into stack

235. Lowest Common Ancestor of a Binary Search Tree

 思路:

  • 两个值都在左边,则LCA在左边
  • 两个值都在右边,则LCA在右边
  • 一个在左一个在右,则说明LCA就是当前的root节点。
  • 为什么会少些return, 什么时候用return!!!!!!!!(错了几次)

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
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; } }; 

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

 

101. Symmetric Tree

recursive: bool function, check function value when return

 669. Trim a Binary Search Tree

If the root value in the range [L, R]
      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

  recursive

(iterative !AC)

257. Binary Tree Paths

recursive: ; path + to_string(val)

iterative: vector<string> res;
        if (root == NULL) return res;
        stack<TreeNode*> s;
        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;
111. Minimum Depth of Binary Tree

基本思路与找max depth 类似,但是会忽略单边为nulll的情况

107. Binary Tree Level Order Traversal II

 用BFS

DFS

Inorder Traversal:

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)

Preorder Traversal:

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)

Postorder Traversal:

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);

string

14. Longest Common Prefix

Logic goes something like this:

  1. Pick a character at i=0th location and compare it with the character at that location in every string.

  2. If anyone doesn’t have that just return “”

  3. Else append that character in to the result.

  4. Increment i and do steps 1-3 till the length of that string.

  5. return result

344. Reverse String

two pointers- swap

13. Roman to Integer

后一个字母大于前一个字母 sum-- else sum++

67. Add Binary

a[i] - '0'
while carry == 1
string and char的区别
carry 先加a 再 加 b

28. Implement strStr()

  bugs: 边界问题没有处理好

思路: 先匹配needle 和 haystack第一字符的位置,后用substr 取出haystack的字符来比较 substr(起始位置,长度)

557. Reverse Words in a String III

two pointers, 当不是空格时,移j到空格处后,reverse字符串。

bug: 字符比较只能用' '即 char

383. Ransom Note

unordered_map - ++map[magazine[i]]; if (--map[str] < 0) return false;

70. Climbing Stairs

fibonacci numbers

take the initial as 1 and 2

 

 

 

转载于:https://www.cnblogs.com/derekleetcode/p/8284545.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值