Feiyang's Blogs 2020-11-13T13:36:40.166Z http://yoursite.com/ Feiyang Chen Hexo LeetCode 450. Delete Node in a BST http://yoursite.com/2020/11/13/Delete-Node-in-a-BST/ 2020-11-13T13:33:01.000Z 2020-11-13T13:36:40.166Z 题目

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

1. Search for a node to remove.
2. If the node is found, delete the node.

Follow up: Can you solve it with time complexity `O(height of tree)`?

Example 1:

Example 2:

Example 3:

Constraints:

• The number of nodes in the tree is in the range `[0, 10^4]`.
• `-10^5 <= Node.val <= 10^5`
• Each node has a unique value.
• root is a valid binary search tree.
• `-10^5 <= key <= 10^5`

## 思路

1. 被删除节点没有左子树：返回其右子树
2. 被删除节点节点没有右子树：返回其左子树
3. 被删除节点既有左子树，又有右子树：
1）查找到其右子树的最小值的节点，替换掉被删除的节点，并删除找到的最小节点
2）查找到其左子树的最大值的节点，替换掉被删除的节点，并删除找到的最大节点

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given a root node reference of a BST and a key, delete the node with t
LeetCode 952. Largest Component Size by Common Factor http://yoursite.com/2020/11/13/Largest-Component-Size-by-Common-Factor/ 2020-11-13T13:10:37.000Z 2020-11-13T13:17:32.983Z 题目

Given a non-empty array of unique positive integers `A`, consider the following graph:

• There are `A.length` nodes, labelled `A` to `A[A.length - 1]`;
• There is an edge between `A[i]` and `A[j]` if and only if `A[i]` and `A[j]` share a common factor greater than 1.

Return the size of the largest connected component in the graph.

Example 1:

Example 2:

Example 3:

Note:

• `1 <= A.length <= 20000`
• `1 <= A[i] <= 100000`

## 思路

For each number, union itself with all its factors.

E.g. 6, union(6,2), union(6,3)

Time complexity: \$𝑂(Σ𝑠𝑞𝑟𝑡(𝐴[𝑖]))\$
Space complexity: \$𝑂(𝑚𝑎𝑥(𝐴))\$

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given a non-empty array of unique positive integers <code>A</code>, co
LeetCode 969. Pancake Sorting http://yoursite.com/2020/11/10/Pancake-Sorting/ 2020-11-10T13:19:49.000Z 2020-11-10T13:26:31.852Z 题目

Given an array of integers `arr`, sort the array by performing a series of pancake flips.

In one pancake flip we do the following steps:

• Choose an integer `k` where `1 <= k <= arr.length`.
• Reverse the sub-array `arr[1...k]`.

For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so arr = `[1,2,3,4]` after the pancake flip at `k = 3`.

Return the `k`-values corresponding to a sequence of pancake flips that sort `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.

Example 1:

Example 2:

Constraints:

• `1 <= arr.length <= 100`
• `1 <= arr[i] <= arr.length`
• All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given an array of integers <code>arr</code>, sort the array by perform
LeetCode 470. Implement Rand10() Using Rand7() http://yoursite.com/2020/11/03/Implement-Rand10-Using-Rand7/ 2020-11-03T13:53:10.000Z 2020-11-03T13:58:28.724Z 题目

Given the API `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn’t call any other API. Please do not use a language’s built-in random API.

Each test case will have one internal argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is not an argument passed to `rand10()`.

• What is the expected value for the number of calls to `rand7()` function?
• Could you minimize the number of calls to `rand7()`?

Example 1:

Example 2:

Example 3:

Constraints:

• `1 <= n <= 10^5`

## 思路

• Approach 1: Rejection Sampling
• Approach 2: Utilizing out-of-range samples

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given the <strong>API</strong> <code>rand7()</code> that generates a u
LeetCode 436. Find Right Interval http://yoursite.com/2020/11/03/Find-Right-Interval/ 2020-11-03T13:14:51.000Z 2020-11-03T13:33:11.989Z 题目

You are given an array of `intervals`, where `intervals[i] = [start_i, end_i]` and each `start_i` is unique.

The right interval for an interval `i` is an interval `j` such that `start_j >= end_i` and `start_j` is minimized.

Return an array of right interval indices for each interval `i`. If no right interval exists for interval `i`, then put `-1` at index `i`.

Example 1:

Example 2:

Example 3:

Constraints:

• `1 <= intervals.length <= 2 * 10^4`
• `intervals[i].length == 2`
• `-106 <= start_i <= end_i <= 106`
• The start point of each interval is unique.

## 思路

Sort + Binary Search.
First, `sorted` every interval by `interval`, record a `tuple(interval, i, interval)`.
Second, `bisect.bisect_left` every interval by `interval`, return `index`, record `r = index`.
Last, `res[i] = interval[r] = index`.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>You are given an array of <code>intervals</code>, where <code>interval
LeetCode 412. Fizz Buzz http://yoursite.com/2020/11/03/Fizz-Buzz/ 2020-11-03T12:46:03.000Z 2020-11-03T12:49:22.540Z 题目

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

## 思路

• Approach 1: Naive Approach
• Approach 2: String Concatenation
• Approach 3: Hash it!

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Write a program that outputs the string representation of numbers from
LeetCode 983. Minimum Cost For Tickets http://yoursite.com/2020/10/29/Minimum-Cost-For-Tickets/ 2020-10-29T13:41:18.000Z 2020-10-29T13:48:55.115Z 题目

In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array `days`. Each day is an integer from `1` to `365`.

Train tickets are sold in 3 different ways:

• a 1-day pass is sold for `costs` dollars;
• a 7-day pass is sold for `costs` dollars;
• a 30-day pass is sold for `costs` dollars.

The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.

Return the minimum number of dollars you need to travel every day in the given list of `days`.

Example 1:

Example 2:

Note:

• `1 <= days.length <= 365`
• `1 <= days[i] <= 365`
• `days` is in strictly increasing order.
• `costs.length == 3`
• `1 <= costs[i] <= 1000`

## 思路

DP.

• `dp[i] = dp[i - 1]` 当第i天不用旅行
• `dp[i] = min(dp[i - 1] + costs, dp[i - 7] + costs, dp[i - 30] + costs)` 当第i天需要旅行

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>In a country popular for train travel, you have planned some train tra
LeetCode 404. Sum of Left Leaves http://yoursite.com/2020/10/29/Sum-of-Left-Leaves/ 2020-10-29T13:17:32.000Z 2020-10-29T13:20:59.424Z 题目

Find the sum of all left leaves in a given binary tree.

Example:

Recursion.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Find the sum of all left leaves in a given binary tree.</p> <p><strong
LeetCode 1032. Stream of Characters http://yoursite.com/2020/09/11/Stream-of-Characters/ 2020-09-11T10:17:27.000Z 2020-09-11T10:22:56.198Z 题目

Implement the `StreamChecker` class as follows:

• `StreamChecker(words)`: Constructor, init the data structure with the given words.
• `query(letter)`: returns true if and only if for some `k >= 1`, the last `k` characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.

Example:

Note:

• `1 <= words.length <= 2000`
• `1 <= words[i].length <= 2000`
• Words will only consist of lowercase English letters.
• Queries will only consist of lowercase English letters.
• The number of queries is at most 40000.

## 思路

Python by search in Trie [w/ Visualization]

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Implement the <code>StreamChecker</code> class as follows:</p> <ul> <l
LeetCode 497. Random Point in Non-overlapping Rectangles http://yoursite.com/2020/08/31/Random-Point-in-Non-overlapping-Rectangles/ 2020-08-31T15:37:13.000Z 2020-08-31T17:54:56.482Z 题目

Given a list of non-overlapping axis-aligned rectangles `rects`, write a function `pick` which randomly and uniformily picks an integer point in the space covered by the rectangles.

Note:

1. An integer point is a point that has integer coordinates.
2. A point on the perimeter of a rectangle is included in the space covered by the rectangles.
3. `i`th rectangle = `rects[i] = [x1,y1,x2,y2]`, where `[x1, y1]` are the integer coordinates of the bottom-left corner, and `[x2, y2]` are the integer coordinates of the top-right corner.
4. length and width of each rectangle does not exceed `2000`.
5. `1 <= rects.length <= 100`
6. `pick` return a point as an array of integer coordinates `[p_x, p_y]`
7. `pick` is called at most `10000` times.

Example 1:

Example 2:

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. `Solution`‘s constructor has one argument, the array of rectangles `rects`. `pick` has no arguments. Arguments are always wrapped with a list, even if there aren’t any.

## 思路

1. Choose a rect, then choose a point inside it.
2. The bigger the rectangle, the higher the probability of it getting chosen.

## 代码

]]>
LeetCode 905. Sort Array By Parity http://yoursite.com/2020/08/31/Sort-Array-By-Parity/ 2020-08-31T15:30:08.000Z 2020-08-31T15:35:37.315Z 题目

Given an array `A` of non-negative integers, return an array consisting of all the even elements of `A`, followed by all the odd elements of `A`.

You may return any answer array that satisfies this condition.

Example 1:

Note:

• `1 <= A.length <= 5000`
• `0 <= A[i] <= 5000`

## 思路

• Approach 1: Sort
Use a custom comparator when sorting, to sort by parity.
Time Complexity: O(NlogN), Space Complexity: O(N)
• Approach 2: Two Pass
Write all the even elements first, then write all the odd elements.
Time Complexity: O(N), Space Complexity: O(N)
• Approach 3: In-Place
Like quicksort.
Time Complexity: O(N), Space Complexity: O(1)

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given an array <code>A</code> of non-negative integers, return an arra
LeetCode 143. Reorder List http://yoursite.com/2020/08/28/Reorder-List/ 2020-08-28T11:34:54.000Z 2020-08-28T11:38:58.097Z 题目

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example 1:

Example 2:

## 思路

split_list(mid-point finding), reverse_list, merge_list的融合体。

## 代码

]]>
LeetCode 824. Goat Latin http://yoursite.com/2020/08/28/Goat-Latin/ 2020-08-28T10:35:56.000Z 2020-08-28T10:54:02.795Z 题目

A sentence `S` is given, composed of words separated by spaces. Each word consists of lowercase and uppercase letters only.

We would like to convert the sentence to “Goat Latin“ (a made-up language similar to Pig Latin.)

The rules of Goat Latin are as follows:

• If a word begins with a vowel (a, e, i, o, or u), append `"ma"` to the end of the word.
For example, the word ‘apple’ becomes ‘applema’.
• If a word begins with a consonant (i.e. not a vowel), remove the first letter and append it to the end, then add `"ma"`.
For example, the word “goat” becomes “oatgma”.
• Add one letter `'a'` to the end of each word per its word index in the sentence, starting with 1.
For example, the first word gets `"a"` added to the end, the second word gets `"aa"` added to the end and so on.

Return the final sentence representing the conversion from `S` to Goat Latin.

Example 1:

Example 2:

Notes:

• `S` contains only uppercase, lowercase and spaces. Exactly one space between each word.
• `1 <= S.length <= 150`.

## 思路

Easy题，但是需要注意一下这题的时间复杂度不是`O(n)`，是`O(n^2)` !!!

• `+`的时间复杂度是`O(n^2)`,
• `join`的时间复杂度是`O(n)`.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>A sentence <code>S</code> is given, composed of words separated by spa
LeetCode 967. Numbers With Same Consecutive Differences http://yoursite.com/2020/08/26/Numbers-With-Same-Consecutive-Differences/ 2020-08-26T12:26:33.000Z 2020-08-26T12:30:38.032Z 题目

Return all non-negative integers of length `N` such that the absolute difference between every two consecutive digits is `K`.

Note that every number in the answer must not have leading zeros except for the number `0` itself. For example, `01` has one leading zero and is invalid, but `0` is valid.

You may return the answer in any order.

Example 1:

Example 2:

Note:

• `1 <= N <= 9`
• `0 <= K <= 9`

DFS.

## 代码

]]>
LeetCode 1103. Distribute Candies to People http://yoursite.com/2020/08/26/Distribute-Candies-to-People/ 2020-08-26T12:20:42.000Z 2020-08-26T12:24:25.165Z 题目

We distribute some number of `candies`, to a row of `n = num_people` people in the following way:

We then give 1 candy to the first person, 2 candies to the second person, and so on until we give `n` candies to the last person.

Then, we go back to the start of the row, giving `n + 1` candies to the first person, `n + 2` candies to the second person, and so on until we give `2 * n` candies to the last person.

This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).

Return an array (of length `num_people` and sum `candies`) that represents the final distribution of candies.

Example 1:

Example 2:

Constraints:

• 1 <= candies <= 10^9
• 1 <= num_people <= 1000

Simulation.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>We distribute some number of <code>candies</code>, to a row of <code>n
LeetCode 435. Non-overlapping Intervals http://yoursite.com/2020/08/26/Non-overlapping-Intervals/ 2020-08-26T12:04:51.000Z 2020-08-26T12:16:42.534Z 题目

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Example 1:

Example 2:

Example 3:

Note:

1. You may assume the interval’s end point is always bigger than its start point.
2. Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.

Sort + Greedy.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given a collection of intervals, find the minimum number of intervals
LeetCode 409. Longest Palindrome http://yoursite.com/2020/08/14/Longest-Palindrome/ 2020-08-14T08:15:04.000Z 2020-08-14T08:18:38.442Z 题目

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example `"Aa"` is not considered a palindrome here.

Note:

Assume the length of given string will not exceed 1,010.

Example:

## 思路

Greedy.

Intuition:

A palindrome consists of letters with equal partners, plus possibly a unique center (without a partner). The letter `i` from the left has its partner `i` from the right. For example in `'abcba'`, `'aa'` and `'bb'` are partners, and `'c'` is a unique center.

Imagine we built our palindrome. It consists of as many partnered letters as possible, plus a unique center if possible. This motivates a greedy approach.

Algorithm:

For each letter, say it occurs `v` times. We know we have `v // 2 * 2` letters that can be partnered for sure. For example, if we have `'aaaaa'`, then we could have `'aaaa'` partnered, which is `5 // 2 * 2 = 4` letters partnered.

At the end, if there was any `v % 2 == 1`, then that letter could have been a unique center. Otherwise, every letter was partnered. To perform this check, we will check for `v % 2 == 1 and ans % 2 == 0`, the latter meaning we haven’t yet added a unique center to the answer.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given a string which consists of lowercase or uppercase letters, find
LeetCode 1286. Iterator for Combination http://yoursite.com/2020/08/13/Iterator-for-Combination/ 2020-08-13T07:38:37.000Z 2020-08-13T07:41:59.484Z 题目

Design an Iterator class, which has:

• A constructor that takes a string `characters` of sorted distinct lowercase English letters and a number `combinationLength` as arguments.
• A function `next()` that returns the next combination of length `combinationLength` in lexicographical order.
• A function `hasNext()` that returns `True` if and only if there exists a next combination.

Example:

Constraints:

• `1 <= combinationLength <= characters.length <= 15`
• There will be at most `10^4` function calls per test.
• It’s guaranteed that all calls of the function `next` are valid.

## 思路

Python built-in `itertools.combinations`.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Design an Iterator class, which has:</p> <ul> <li>A constructor that t
LeetCode 119. Pascal's Triangle II http://yoursite.com/2020/08/12/Pascal-s-Triangle-II/ 2020-08-12T10:54:43.000Z 2020-08-12T10:56:54.703Z 题目

Given a non-negative index k where k ≤ 33, return the k^th index row of the Pascal’s triangle.

Note that the row index starts from 0.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Could you optimize your algorithm to use only O(k) extra space?

DP.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given a non-negative index <em>k</em> where <em>k ≤ 33</em>, return th
LeetCode 274. H-Index http://yoursite.com/2020/08/11/H-Index/ 2020-08-11T07:49:22.000Z 2020-08-11T07:53:09.354Z 题目

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher’s h-index.

According to the definition of h-index on Wikipedia: “A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each.”

Example:

Note:

If there are several possible values for h, the maximum one is taken as the h-index.

Binary Search.

## 代码

]]>
<h2 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h2><p>Given an array of citations (each citation is a non-negative integer)