总览

思考题:如何用代码实现针对代码计算其时间复杂度?

需要深入学习的问题

  1. 背包问题

  2. 滑动窗口算法

  3. 马拉车回文判定算法

  4. 树的迭代遍历(不使用递归)

附加题

  1. 将树打印到控制台。

如果问最短,最少,BFS
如果问连通性,静态就是 DFS,BFS,动态就 UF
如果问依赖性就 topo sort
DAG 的问题就 dfs+memo
矩阵和 Array 通常都是 DP
问数量的通常都是 DP
问是否可以,也很有可能 DP
求所有解的,基本 backtracking
排序总是可以想一想的
万事总可以想HashMap
找规律试试Stack

滑动窗口算法

滑动窗口类型的题目经常是用来执行数组或是链表上某个区间(窗口)上的操作。比如找最长的全为1的子数组长度。滑动窗口一般从第一个元素开始,一直往右边一个一个元素挪动。当然了,根据题目要求,我们可能有固定窗口大小的情况,也有窗口的大小变化的情况。

下面是一些我们用来判断我们可能需要上滑动窗口策略的方法:

  • 这个问题的输入是一些线性结构:比如链表呀,数组啊,字符串啊之类的

  • 让你去求最长/最短子字符串或是某些特定的长度要求

经典题目:

Maximum Sum Subarray of Size K (easy)

Smallest Subarray with a given sum (easy)

Longest Substring with K Distinct Characters (medium)

Fruits into Baskets (medium)

No-repeat Substring (hard)

Longest Substring with Same Letters after Replacement (hard)

Longest Subarray with Ones after Replacement (hard)

LeetCode 239. Sliding Window Maximum (hard)

LeetCode 480. Sliding Window Median (hard)

LeetCode 3. Longest Substring Without Repeating Characters (medium)

LeetCode 76. Minimum Window Substring (hard)

LeetCode 395. Longest Substring with At Least K Repeating Characters (medium)

LeetCode 567. Permutation in String (medium)

LeetCode 438. Find All Anagrams in a String (medium)

LeetCode 209. Minimum Size Subarray Sum (medium)

LeetCode 424. Longest Repeating Character Replacement (medium)

LeetCode 1208. Get Equal Substrings Within Budget (medium)

LeetCode 904. Fruit Into Baskets (medium)

LeetCode 978. Longest Turbulent Subarray (medium)

LeetCode 992. Subarrays with K Different Integers (hard)

LeetCode 995. Minimum Number of K Consecutive Bit Flips (hard)

LeetCode 1040. Moving Stones Until Consecutive II (medium)

LeetCode 1052. Grumpy Bookstore Owner (medium)

LeetCode 1074. Number of Submatrices That Sum to Target (hard)

整体思路

滑动窗口算法的抽象思想:

int left = 0, right = 0;

while (right < s.size()) {
window.add(s[right]);
right++;

    while (valid) {
        window.remove(s[left]);
        left++;
    }
}

其中 window 的数据类型可以视具体情况而定,比如上述题目都使用哈希表充当计数器,当然你也可以用一个数组实现同样效果,因为我们只处理英文字母。

稍微麻烦的地方就是这个 valid 条件,为了实现这个条件的实时更新,我们可能会写很多代码。比如前两道题,看起来解法篇幅那么长,实际上思想还是很简单,只是大多数代码都在处理这个问题而已。

Two Pointer

  1. 76. Minimum Window Substring

  2. 209. Minimum Size Subarray Sum

  3. 239. Sliding Window Maximum

  4. 424. Longest Repeating Character Replacement

  5. 438. Find All Anagrams in a String

  6. 567. Permutation in String

  7. 713. Subarray Product Less Than K

  8. 763. Partition Labels

Pair with Target Sum (easy) Remove Duplicates (easy) Squaring a Sorted Array (easy) Triplet Sum to Zero (medium) Triplet Sum Close to Target (medium) Triplets with Smaller Sum (medium) Subarrays with Product Less than a Target (medium) Dutch National Flag Problem (medium)

双指针是这样的模式:两个指针朝着左右方向移动(双指针分为同向双指针和异向双指针),直到他们有一个或是两个都满足某种条件。双指针通常用在排好序的数组或是链表中寻找对子。比如,你需要去比较数组中每个元素和其他元素的关系时,你就需要用到双指针了。

我们需要双指针的原因是:如果你只用一个指针的话,你得来回跑才能在数组中找到你需要的答案。这一个指针来来回回的过程就很耗时和浪费空间了 — 这是考虑算法的复杂度分析的时候的重要概念。虽然brute force一个指针的解法可能会奏效,但时间复杂度一般会是O(n²)。在很多情况下,双指针能帮助我们找到空间或是时间复杂度更低的解。

识别使用双指针的招数:

  • 一般来说,数组或是链表是排好序的,你得在里头找一些组合满足某种限制条件

  • 这种组合可能是一对数,三个数,或是一个子数组

经典题目:

Pair with Target Sum (easy)

Remove Duplicates (easy)

Squaring a Sorted Array (easy)

Triplet Sum to Zero (medium)

Triplet Sum Close to Target (medium)

Triplets with Smaller Sum (medium)

Subarrays with Product Less than a Target (medium)

Dutch National Flag Problem (medium)

LeetCode 32. Longest Valid Parentheses (hard)

LeetCode 76. Minimum Window Substring (hard)

LeetCode 799. Champagne Tower (medium)

LeetCode 962. Maximum Width Ramp (medium)

LeetCode 1124. Longest Well-Performing Interval (medium)

Fast & Slow pointers, 快慢指针类型

这种模式,有一个非常出门的名字,叫龟兔赛跑。咱们肯定都知道龟兔赛跑啦。但还是再解释一下快慢指针:这种算法的两个指针的在数组上(或是链表上,序列上)的移动速度不一样。还别说,这种方法在解决有环的链表和数组时特别有用。

通过控制指针不同的移动速度(比如在环形链表上),这种算法证明了他们肯定会相遇的。快的一个指针肯定会追上慢的一个(可以想象成跑道上面跑得快的人套圈跑得慢的人)。

咋知道需要用快慢指针模式勒?

  • 问题需要处理环上的问题,比如环形链表和环形数组

  • 当你需要知道链表的长度或是某个特别位置的信息的时候

那啥时候用快慢指针而不是上面的双指针呢?

  • 有些情形下,咱们不应该用双指针,比如我们在单链表上不能往回移动的时候。一个典型的需要用到快慢指针的模式的是当你需要去判断一个链表是否是回文的时候。

LinkedList Cycle (easy)

Start of LinkedList Cycle (medium)

Happy Number (medium)

Middle of the LinkedList (easy)

Merge Intervals,区间合并类型

区间合并模式是一个用来处理有区间重叠的很高效的技术。在设计到区间的很多问题中,通常咱们需要要么判断是否有重叠,要么合并区间,如果他们重叠的话。这个模式是这么起作用的:

给两个区间,一个是a,另外一个是b。别小看就两个区间,他们之间的关系能跑出来6种情况。详细的就看图啦。

怎么识别啥时候用合并区间模式呀?

  • 当你需要产生一堆相互之间没有交集的区间的时候

  • 当你听到重叠区间的时候

Merge Intervals (medium)

Insert Interval (medium)

Intervals Intersection (medium)

Conflicting Appointments (medium)

Cyclic Sort,循环排序

这种模式讲述的是一直很好玩的方法:可以用来处理数组中的数值限定在一定的区间的问题。这种模式一个个遍历数组中的元素,如果当前这个数它不在其应该在的位置的话,咱们就把它和它应该在的那个位置上的数交换一下。你可以尝试将该数放到其正确的位置上,但这复杂度就会是O(n2)。这样的话,可能就不是最优解了。因此循环排序的优势就体现出来了。

咋鉴别这种模式?

  • 这些问题一般设计到排序好的数组,而且数值一般满足于一定的区间

  • 如果问题让你需要在排好序/翻转过的数组中,寻找丢失的/重复的/最小的元素

Cyclic Sort (easy)

Find the Missing Number (easy)

Find all Missing Numbers (easy)

Find the Duplicate Number (easy)

Find all Duplicate Numbers (easy)

In-place Reversal of a LinkedList,链表翻转

在众多问题中,题目可能需要你去翻转链表中某一段的节点。通常,要求都是你得原地翻转,就是重复使用这些已经建好的节点,而不使用额外的空间。这个时候,原地翻转模式就要发挥威力了。

这种模式每次就翻转一个节点。一般需要用到多个变量,一个变量指向头结点(下图中的current),另外一个(previous)则指向咱们刚刚处理完的那个节点。在这种固定步长的方式下,你需要先将当前节点(current)指向前一个节点(previous),再移动到下一个。同时,你需要将previous总是更新到你刚刚新鲜处理完的节点,以保证正确性。

咱们怎么去甄别这种模式呢?

  • 如果你被问到需要去翻转链表,要求不能使用额外空间的时候

经典题目:

Reverse a LinkedList (easy)

Reverse a Sub-list (medium)

Reverse every K-element Sub-list (medium)

Tree Breadth First Search,树上的BFS

这种模式基于宽搜(Breadth First Search (BFS)),适用于需要遍历一颗树。借助于队列数据结构,从而能保证树的节点按照他们的层数打印出来。打印完当前层所有元素,才能执行到下一层。所有这种需要遍历树且需要一层一层遍历的问题,都能用这种模式高效解决。

这种树上的BFS模式是通过把根节点加到队列中,然后不断遍历直到队列为空。每一次循环中,我们都会把队头结点拿出来(remove),然后对其进行必要的操作。在删除每个节点的同时,其孩子节点,都会被加到队列中。

识别树上的BFS模式:

  • 如果你被问到去遍历树,需要按层操作的方式(也称作层序遍历)

经典题目:

Binary Tree Level Order Traversal (easy)

Reverse Level Order Traversal (easy)

Zigzag Traversal (medium)

Level Averages in a Binary Tree (easy)

Minimum Depth of a Binary Tree (easy)

Level Order Successor (easy)

Connect Level Order Siblings (medium)

Tree Depth First Search,树上的DFS

树形DFS基于深搜(Depth First Search (DFS))技术来实现树的遍历。

咱们可以用递归(或是显示栈,如果你想用迭代方式的话)来记录遍历过程中访问过的父节点。

该模式的运行方式是从根节点开始,如果该节点不是叶子节点,我们需要干三件事:

  1. 需要区别我们是先处理根节点(pre-order,前序),处理孩子节点之间处理根节点(in-order,中序),还是处理完所有孩子再处理根节点(post-order,后序)。

  2. 递归处理当前节点的左右孩子。

识别树形DFS:

  • 你需要按前中后序的DFS方式遍历树

  • 如果该问题的解一般离叶子节点比较近。

经典题目:

Binary Tree Path Sum (easy)

All Paths for a Sum (medium)

Sum of Path Numbers (medium)

Path With Given Sequence (medium)

Count Paths for a Sum (medium)

Two Heaps,双堆类型

很多问题中,我们被告知,我们拿到一大把可以分成两队的数字。为了解决这个问题,我们感兴趣的是,怎么把数字分成两半?使得:小的数字都放在一起,大的放在另外一半。双堆模式就能高效解决此类问题。

正如名字所示,该模式用到了两个堆,是不是很难猜?一个最小堆用来找最小元素;一个最大堆,拿到最大元素。这种模式将一半的元素放在最大堆中,这样你可以从这一堆中秒找到最大元素。同理,把剩下一半丢到最小堆中,O(1)时间找到他们中的最小元素。通过这样的方式,这一大堆元素的中位数就可以从两个堆的堆顶拿到数字,从而计算出来。

判断双堆模式的秘诀:

  • 这种模式在优先队列,计划安排问题(Scheduling)中有奇效

  • 如果问题让你找一组数中的最大/最小/中位数

  • 有时候,这种模式在涉及到二叉树数据结构时也特别有用

经典题目:

Find the Median of a Number Stream (medium)

Sliding Window Median (hard)

Maximize Capital (hard)

Subsets,子集类型,一般都是使用多重DFS

超级多的编程面试问题都会涉及到排列和组合问题。子集问题模式讲的是用BFS来处理这些问题。

这个模式是这样的:

给一组数字 [1, 5, 3]

  1. 我们从空集开始:[[]]

  2. 把第一个数(1),加到之前已经存在的集合中:[[], [1]];

  3. 把第二个数(5),加到之前的集合中得到:[[], [1], [5], [1,5]];

  4. 再加第三个数(3),则有:[[], [1], [5], [1,5], [3], [1,3], [5,3], [1,5,3]].

如果判断这种子集模式:

  • 问题需要咱们去找数字的组合或是排列

经典题目:

Subsets (easy)

Subsets With Duplicates (easy)

Permutations (medium)

String Permutations by changing case (medium)

Balanced Parentheses (hard)

Unique Generalized Abbreviations (hard)

Modified Binary Search,改造过的二分

当你需要解决的问题的输入是排好序的数组,链表,或是排好序的矩阵,要求咱们寻找某些特定元素。这个时候的不二选择就是二分搜索。这种模式是一种超级牛的用二分来解决问题的方式。

对于一组满足上升排列的数集来说,这种模式的步骤是这样的:

  1. 首先,算出左右端点的中点。最简单的方式是这样的:middle = (start + end) / 2。但这种计算方式有不小的概率会出现整数越界。因此一般都推荐另外这种写法:middle = start + (end — start) / 2

  2. 如果要找的目标改好和中点所在的数值相等,我们返回中点的下标就行

  3. 如果目标不等的话:我们就有两种移动方式了如果目标比中点在的值小(key < arr[middle]):将下一步搜索空间放到左边(end = middle - 1)

  4. 如果比中点的值大,则继续在右边搜索,丢弃左边:left = middle + 1

经典题目:

Order-agnostic Binary Search (easy)

Ceiling of a Number (medium)

Next Letter (medium)

Number Range (medium)

Search in a Sorted Infinite Array (medium)

Minimum Difference Element (medium)

Bitonic Array Maximum (easy)

Top ‘K’ Elements,前K个系列

任何让我们求解最大/最小/最频繁的K个元素的题,都遵循这种模式。

用来记录这种前K类型的最佳数据结构就是堆了(译者注:在Java中,改了个名,叫优先队列(PriorityQueue))。这种模式借助堆来解决很多这种前K个数值的问题。

这个模式是这样的:

  1. 根据题目要求,将K个元素插入到最小堆或是最大堆。

  2. 遍历剩下的还没访问的元素,如果当前出来到的这个元素比堆顶元素大,那咱们把堆顶元素先删除,再加当前元素进去。

注意这种模式下,咱们不需要去排序数组,因为堆具有这种良好的局部有序性,这对咱们需要解决问题就够了。

识别最大K个元素模式:

  • 如果你需要求最大/最小/最频繁的前K个元素

  • 如果你需要通过排序去找一个特定的数

经典题目:

Top ‘K’ Numbers (easy)

Kth Smallest Number (easy)

‘K’ Closest Points to the Origin (easy)

Connect Ropes (easy)

Top ‘K’ Frequent Numbers (medium)

Frequency Sort (medium)

Kth Largest Number in a Stream (medium)

‘K’ Closest Numbers (medium)

Maximum Distinct Elements (medium)

Sum of Elements (medium)

Rearrange String (hard)

K-way merge,多路归并

K路归并能帮咱们解决那些涉及到多组排好序的数组的问题。

每当你的输入是K个排好序的数组,你就可以用堆来高效顺序遍历其中所有数组的所有元素。你可以将每个数组中最小的一个元素加入到最小堆中,从而得到全局最小值。当我们拿到这个全局最小值之后,再从该元素所在的数组里取出其后面紧挨着的元素,加入堆。如此往复直到处理完所有的元素。

该模式是这样的运行的:

  1. 把每个数组中的第一个元素都加入最小堆中

  2. 取出堆顶元素(全局最小),将该元素放入排好序的结果集合里面

  3. 将刚取出的元素所在的数组里面的下一个元素加入堆

  4. 重复步骤2,3,直到处理完所有数字

识别K路归并:

  • 该问题的输入是排好序的数组,链表或是矩阵

  • 如果问题让咱们合并多个排好序的集合,或是需要找这些集合中最小的元素

经典题目:

Merge K Sorted Lists (medium)

Kth Smallest Number in M Sorted Lists (Medium)

Kth Smallest Number in a Sorted Matrix (Hard)

Smallest Number Range (Hard)

Topological Sort (Graph),拓扑排序类型

拓扑排序模式用来寻找一种线性的顺序,这些元素之间具有依懒性。比如,如果事件B依赖于事件A,那A在拓扑排序顺序中排在B的前面。

这种模式定义了一种简单方式来理解拓扑排序这种技术。

这种模式是这样奏效的:

  1. 初始化

    1. 借助于HashMap将图保存成邻接表形式。

    2. 找到所有的起点,用HashMap来帮助记录每个节点的入度

  2. 创建图,找到每个节点的入度

    1. 利用输入,把图建好,然后遍历一下图,将入度信息记录在HashMap中

  3. 找所有的起点

    1. 所有入度为0的节点,都是有效的起点,而且我们讲他们都加入到一个队列中

  4. 排序

    1. 对每个起点,执行以下步骤

      1. 把它加到结果的顺序中

      2. 将其在图中的孩子节点取到

      3. 将其孩子的入度减少1

      4. 如果孩子的入度变为0,则改孩子节点成为起点,将其加入队列中

    2. 重复(a)过程,直到起点队列为空。

拓扑排序模式识别:

  • 待解决的问题需要处理无环图

  • 你需要以一种有序的秩序更新输入元素

  • 需要处理的输入遵循某种特定的顺序

经典题目:

Topological Sort (medium)

Tasks Scheduling (medium)

Tasks Scheduling Order (medium)

All Tasks Scheduling Orders (hard)

Alien Dictionary (hard)

Backtrack,回溯

参考 46. Permutations 认真学习一下回溯思想。

玩回溯,一定要画出递归调用树。

回溯优化,重要的是,要学会剪枝!

附加题

  1. 写程序尝试生成递归调用树。

Greedy,贪心

Brute Force,暴力破解

选择排序,冒泡排序,在有序数组中的顺序查找等等都属于暴力破解的解法。

Decrease and Conquer,减治法

Divide and Conquer,分治法

Transform and Conquer,变知法

Dynamic Programming,动态规划

0/1 Knapsack,0/1背包

0/1 Knapsack,0/1背包问题

Equal Subset Sum Partition,相等子集划分问题

Subset Sum,子集和问题

Minimum Subset Sum Difference,子集和的最小差问题

Count of Subset Sum,相等子集和的个数问题

Target Sum,寻找目标和的问题

Unbounded Knapsack,无限背包

Unbounded Knapsack,无限背包

Rod Cutting,切钢条问题

Coin Change,换硬币问题

Minimum Coin Change,凑齐每个数需要的最少硬币问题

Maximum Ribbon Cut,丝带的最大值切法

Fibonacci Numbers,斐波那契数列

Fibonacci numbers,斐波那契数列问题

Staircase,爬楼梯问题

Number factors,分解因子问题

Minimum jumps to reach the end,蛙跳最小步数问题

Minimum jumps with fee,蛙跳带有代价的问题

House thief,偷房子问题

Palindromic Subsequence,回文子系列

Longest Palindromic Subsequence,最长回文子序列

Longest Palindromic Substring,最长回文子字符串

Count of Palindromic Substrings,最长子字符串的个数问题

Minimum Deletions in a String to make it a Palindrome,怎么删掉最少字符构成回文

Palindromic Partitioning,怎么分配字符,形成回文

Longest Common Substring,最长子字符串系列

Longest Common Substring,最长相同子串

Longest Common Subsequence,最长相同子序列

Minimum Deletions & Insertions to Transform a String into another,字符串变换

Longest Increasing Subsequence,最长上升子序列

Maximum Sum Increasing Subsequence,最长上升子序列和

Shortest Common Super-sequence,最短超级子序列

Minimum Deletions to Make a Sequence Sorted,最少删除变换出子序列

Longest Repeating Subsequence,最长重复子序列

Subsequence Pattern Matching,子序列匹配

Longest Bitonic Subsequence,最长字节子序列

Longest Alternating Subsequence,最长交差变换子序列

Edit Distance,编辑距离

Strings Interleaving,交织字符串

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * = 1. Two Sum
 *
 * https://leetcode.com/problems/two-sum/description/[Two Sum - LeetCode]
 *
 * Given an array of integers, return indices of the two numbers such that they
 * add up to a specific target.
 *
 * You may assume that each input would have exactly one solution, and you may
 * not use the same element twice.
 *
 * .Example:
 * [source]
 * ----
 * Given nums = [2, 7, 11, 15], target = 9,
 *
 * Because nums[0] + nums[1] = 2 + 7 = 9,
 * return [0, 1].
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-06-30
 */
public class _0001_TwoSum {
    /**
     * 原始算法,时间复杂度为 `O(n^2^)`.
     *
     * @param nums   数组
     * @param target 目标
     * @return 结果
     */
    public static int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return null;
        }
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }

        return null;
    }

    /**
     * 优化后的算法,时间复杂度减低为 `O(n)`, 空间复杂度提高了。
     *
     * @param nums   数组
     * @param target 目标
     * @return 结果
     */
    public static int[] twoSumO1(int[] nums, int target) {
        if (nums == null || nums.length < 2) {
            return null;
        }

        Map<Integer, Integer> diffNumToIndexMap = new HashMap<>(nums.length * 4 / 3);
        for (int i = 0; i < nums.length; i++) {
            if (diffNumToIndexMap.containsKey(nums[i])) {
                return new int[]{diffNumToIndexMap.get(nums[i]), i};
            } else {
                diffNumToIndexMap.put(target - nums[i], i);
            }
        }

        return null;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{4, 9, 2, 7, 11, 15};
        int target = 8;
        System.out.println(Arrays.toString(twoSumO1(nums, target)));
    }
}

2. Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;
import com.diguage.algorithm.util.ListNodeUtils;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 2. Add Two Numbers
 *
 * https://leetcode.com/problems/add-two-numbers/description/[Add Two Numbers - LeetCode]
 *
 * You are given two non-empty linked lists representing two non-negative
 * integers. The digits are stored in reverse order and each of their nodes
 * contain a single digit. Add the two numbers and return it as a linked list.
 *
 * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
 *
 * .Example:
 * [source]
 * ----
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * Output: 7 -> 0 -> 8
 * Explanation: 342 + 465 = 807.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-09-17 11:42
 */
public class _0002_AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//        ListNode h1 = l1;
//        ListNode h2 = l2;
//        ListNode mergeList = null;
//        int carryOver = 0;
//        while (Objects.nonNull(h1) && Objects.nonNull(h2)) {
//            int v1 = h1.val;
//            int v2 = h2.val;
//            int newVal = v1 + v2 + carryOver;
//            if (newVal >= 10) {
//                carryOver = 1;
//                newVal -= 10;
//            } else {
//                carryOver = 0;
//            }
//            ListNode listNode = new ListNode(newVal);
//            listNode.next = mergeList;
//            mergeList = listNode;
//            h1 = h1.next;
//            h2 = h2.next;
//        }
//
//        ListNode rest = null;
//        if (Objects.nonNull(h1)) {
//            rest = h1;
//        }
//        if (Objects.nonNull(h2)) {
//            rest = h2;
//        }
//
//        ListNode restHead = rest;
//        while (Objects.nonNull(rest) && carryOver > 0) {
//            int newVal = rest.val + carryOver;
//            if (newVal >= 10) {
//                carryOver = 1;
//                newVal -= 10;
//            } else {
//                carryOver = 0;
//            }
//            rest.val = newVal;
//            if (Objects.isNull(rest.next) && carryOver > 0) {
//                ListNode carryNode = new ListNode(carryOver);
//                rest.next = carryNode;
//                carryOver = 0;
//            }
//            rest = rest.next;
//        }
//        if (Objects.isNull(restHead) && carryOver > 0) {
//            restHead = new ListNode(carryOver);
//        }
//
//        while (Objects.nonNull(mergeList)) {
//            ListNode next = mergeList.next;
//            mergeList.next = restHead;
//            restHead = mergeList;
//            mergeList = next;
//        }
//
//        return restHead;
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
        ListNode result = l1;
        int digit = 0;
        while (Objects.nonNull(l1.next) && Objects.nonNull(l2.next)) {
            int sum = l1.val + l2.val + digit;
            l1.val = sum % 10;
            digit = sum / 10;
            l1 = l1.next;
            l2 = l2.next;
        }
        int sum = l1.val + l2.val + digit;
        l1.val = sum % 10;
        digit = sum / 10;
        if (Objects.isNull(l1.next) && Objects.nonNull(l2.next)) {
            l1.next = l2.next;
            l1 = l1.next;
        }
        ListNode tail = null;
        ;
        while (digit > 0 && Objects.nonNull(l1)) {
            tail = l1;
            sum = l1.val + digit;
            l1.val = sum % 10;
            digit = sum / 10;
            l1 = l1.next;
        }
        if (digit > 0) {
            tail.next = new ListNode(digit);
        }
        return result;
//        ListNode result = l1;
//        int digit = 0;
//        while (Objects.nonNull(l1.next) && Objects.nonNull(l2.next)) {
//            int sum = l1.val + l2.val + digit;
//            l1.val = sum % 10;
//            digit = sum / 10;
//            l1 = l1.next;
//            l2 = l2.next;
//        }
//        int sum = l1.val + l2.val + digit;
//        l1.val = sum % 10;
//        digit = sum / 10;
//        if (Objects.isNull(l1.next) && Objects.nonNull(l2.next)) {
//            l1.next = l2.next;
//            l1 = l1.next;
//        }
//        while (digit > 0 && Objects.nonNull(l1.next)) {
//            sum = l1.val + digit;
//            l1.val = sum % 10;
//            digit = sum / 10;
//            l1 = l1.next;
//        }
//        if (digit > 0) {
//            l1.next = new ListNode(digit);
//        }
//        return result;
    }


    public static void main(String[] args) {
        _0002_AddTwoNumbers result = new _0002_AddTwoNumbers();
//        ListNode list1 = result.convertNumberToList(1);
//        ListNode list2 = result.convertNumberToList(99);
//        ListNode sum = result.addTwoNumbers(list1, list2);
//        printListNode(sum);
        ListNode list = result.addTwoNumbers(ListNodeUtils.build(Arrays.asList(9, 8)), ListNodeUtils.build(Arrays.asList(8)));
        ListNodeUtils.printListNode(list);
    }


    public ListNode convertNumberToList(int number) {
        ListNode result = null;
        for (int i = number; i > 0; i /= 10) {
            int vaule = i % 10;
            ListNode listNode = new ListNode(vaule);
            if (Objects.isNull(result)) {
                result = listNode;
            } else {
                ListNode last = result;
                while (Objects.nonNull(last.next)) {
                    last = last.next;
                }
                last.next = listNode;
            }
        }
        return result;
    }
}

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * = 3. Longest Substring Without Repeating Characters
 *
 * https://leetcode.com/problems/longest-substring-without-repeating-characters/[Longest Substring Without Repeating Characters - LeetCode]
 *
 * Given a string, find the length of the *longest substring* without repeating characters.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "abcabcbb"
 * Output: 3
 * Explanation: The answer is "abc", with the length of 3.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "bbbbb"
 * Output: 1
 * Explanation: The answer is "b", with the length of 1.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: "pwwkew"
 * Output: 3
 * Explanation: The answer is "wke", with the length of 3.
 * Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-11 21:31
 */
public class _0003_LongestSubstringWithoutRepeatingCharacters {
  /**
   * Runtime: 6 ms, faster than 85.45% of Java online submissions for Longest Substring Without Repeating Characters.
   *
   * Memory Usage: 36.4 MB, less than 99.80% of Java online submissions for Longest Substring Without Repeating Characters.
   */
  public int lengthOfLongestSubstring(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
      return 0;
    }
    int result = 0;
    int length = s.length();
    Map<Character, Integer> charToIndexMap = new HashMap<>(length * 4 / 3);
    for (int i = 0, j = 0; j < length; j++) {
      char aChar = s.charAt(j);
      if (charToIndexMap.containsKey(aChar)) {
        // 这里,如果存在重复的,则从上一个重复字符的下一个字符开始计算。
        Integer index = charToIndexMap.get(aChar);
        if (index + 1 > i) {
          i = index + 1;
        }
      }
      charToIndexMap.put(aChar, j);
      if (j - i + 1 > result) {
        result = j - i + 1;
      }

    }
    return result;
  }

  /**
   * Runtime: 9 ms, faster than 49.55% of Java online submissions for Longest Substring Without Repeating Characters.
   *
   * Memory Usage: 36 MB, less than 99.88% of Java online submissions for Longest Substring Without Repeating Characters.
   */
  public int lengthOfLongestSubstringWithSlidingWindow(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
      return 0;
    }
    int result = 0;
    int length = s.length();
    int head = 0;
    int tail = 0;
    Set<Character> characters = new HashSet<>(length * 4 / 3);
    while (head < length && tail < length) {
      if (!characters.contains(s.charAt(tail))) {
        characters.add(s.charAt(tail));
        tail++;
        if (result < tail - head) {
          result = tail - head;
        }
      } else {
        characters.remove(s.charAt(head));
        head++;
      }
    }
    return result;
  }

  /**
   * Runtime: 221 ms, faster than 5.02% of Java online submissions for Longest Substring Without Repeating Characters.
   *
   * Memory Usage: 37.3 MB, less than 97.43% of Java online submissions for Longest Substring Without Repeating Characters.
   */
  public int lengthOfLongestSubstringWithBruteForce(String s) {
    if (Objects.isNull(s) || s.length() == 0) {
      return 0;
    }
    char[] chars = s.toCharArray();
    int result = 0;
    for (int i = 0; i < chars.length; i++) {
      Set<Character> characters = new HashSet<>(chars.length * 4 / 3);
      for (int j = i; j < chars.length; j++) {
        char aChar = chars[j];
        if (characters.contains(aChar)) {
          break;
        } else {
          characters.add(aChar);
        }
      }
      if (characters.size() > result) {
        result = characters.size();
      }
    }
    return result;
  }

  public static void main(String[] args) {
    _0003_LongestSubstringWithoutRepeatingCharacters result = new _0003_LongestSubstringWithoutRepeatingCharacters();
    System.out.println("2 - " + result.lengthOfLongestSubstring("aab"));
    System.out.println("3 - " + result.lengthOfLongestSubstring("abcabcbb"));
    System.out.println("1 - " + result.lengthOfLongestSubstring("bbbbb"));
    System.out.println("3 - " + result.lengthOfLongestSubstring("pwwkew"));
  }
}

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.

Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
package com.diguage.algorithm.leetcode;

/**
 * = 4. Median of Two Sorted Arrays
 *
 * https://leetcode.com/problems/median-of-two-sorted-arrays/description/[Median of Two Sorted Arrays - LeetCode]
 *
 * There are two sorted arrays nums1 and nums2 of size m and n respectively.
 *
 * Find the median of the two sorted arrays. The overall run time complexity
 * should be latexmath:[O(log(m+n))].
 *
 * .Example 1:
 * [source]
 * ----
 * nums1 = [1, 3]
 * nums2 = [2]
 *
 * The median is 2.0
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * nums1 = [1, 2]
 * nums2 = [3, 4]
 *
 * The median is (2 + 3)/2 = 2.5
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-01
 */
public class _0004_MedianOfTwoSortedArrays {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (isEmpty(nums1) && isEmpty(nums2)) {
            return 0;
        }
        if (isEmpty(nums1)) {
            return singleArray(nums2);
        }
        if (isEmpty(nums2)) {
            return singleArray(nums1);
        }

        int length = nums1.length + nums2.length;
        boolean isOdd = (length & 1) == 1;
        int i1 = 0;
        int i2 = 0;
        int min = nums1[0] < nums2[0] ? nums1[0] : nums2[0];
        int temp = min;
        int last = min;
        int now = min;
        for (int i = 0; i < length; i++) {
            if (i1 < nums1.length && i2 < nums2.length) {
                if (nums1[i1] <= nums2[i2]) {
                    temp = nums1[i1];
                    i1++;
                } else {
                    temp = nums2[i2];
                    i2++;
                }
            } else if (i1 < nums1.length) {
                temp = nums1[i1];
                i1++;
            } else {
                temp = nums2[i2];
                i2++;
            }

            if (i > 0) {
                last = now;
                now = temp;
            }

            if (length / 2 == i) {
                if (isOdd) {
                    return now;
                } else {
                    return ((double) (last + now)) / 2.0;
                }
            }
        }
        return 0;
    }

    private static boolean isEmpty(int[] nums) {
        return nums == null || nums.length == 0;
    }

    public static double findMedianSortedArraysBest(int[] nums1, int[] nums2) {
        // TODO
        return 0;
    }

    private static double singleArray(int[] nums2) {
        boolean isOdd = (nums2.length & 1) == 1;
        if (isOdd) {
            return nums2[nums2.length / 2];
        } else {
            return (nums2[nums2.length / 2 - 1] + nums2[nums2.length / 2]) / 2.0;
        }
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{100001};
        int[] nums2 = new int[]{100000};

        System.out.println(findMedianSortedArrays(nums1, nums2));
    }
}

5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"

解题分析

最简单的方式:使用两个指针,把字符串逐个"拆成"子串,然后留下最大子串即可。可惜,这种算法的时间复杂度是 O(n3)。

没想到,竟然存在时间复杂度为 O(n) 的算法:Manacher’s Algorithm。在维基百科上有解释: Longest palindromic substring - Wikipedia。回头研究研究再补充!

另外,这道题还可以练手动态规划。

参考资料

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 5. Longest Palindromic Substring
 *
 * https://leetcode.com/problems/longest-palindromic-substring/[Longest Palindromic Substring - LeetCode]
 *
 * Given a string s, find the longest palindromic substring in s.
 * You may assume that the maximum length of s is 1000.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "babad"
 * Output: "bab"
 * Note: "aba" is also a valid answer.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "cbbd"
 * Output: "bb"
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-13 11:12
 */
public class _0005_LongestPalindromicSubstring {
  /**
   * Runtime: 1118 ms, faster than 5.01% of Java online submissions for Longest Palindromic Substring.
   *
   * Memory Usage: 37.2 MB, less than 94.36% of Java online submissions for Longest Palindromic Substring.
   */
  public String longestPalindromeBruteForce(String s) {
    if (Objects.isNull(s) || s.length() == 1) {
      return s;
    }
    int maxLength = 1;
    int begin = 0;
    for (int i = 0; i < s.length() - 1; i++) {
      for (int j = i + 1; j < s.length(); j++) {
        // 这里要注意:先判断长度,然后执行回文判断,相当于做了剪枝操作,效率会提高很多。
        if (j - i + 1 > maxLength && isPalindrome(s, i, j)) {
          maxLength = j - i + 1;
          begin = i;
        }
      }
    }
    return s.substring(begin, begin + maxLength);
  }

  private boolean isPalindrome(String s, int low, int high) {
    while (low <= high) {
      if (s.charAt(low) != s.charAt(high)) {
        return false;
      }
      low++;
      high--;
    }
    return true;
  }

  public String longestPalindrome(String s) {
    if (Objects.isNull(s) || s.length() <= 1) {
      return s;
    }
    int start = 0;
    int end = 0;
    for (int i = 0; i < s.length() - 1; i++) {
      int len1 = expandAroundCenter(s, i, i);
      int len2 = expandAroundCenter(s, i, i + 1);
      int len = Math.max(len1, len2);
      if (len > end - start) {
        start = i - (len - 1) / 2;
        end = i + len / 2;
      }
    }
    return s.substring(start, end + 1);
  }

  private int expandAroundCenter(String s, int left, int right) {
    while (0 <= left && right < s.length() && s.charAt(left) == s.charAt(right)) {
      left--;
      right++;
    }
    return right - left - 1;
  }

  public static void main(String[] args) {
    _0005_LongestPalindromicSubstring solution = new _0005_LongestPalindromicSubstring();
    System.out.println("aaabaaa - " + solution.longestPalindrome("cbbd"));
    System.out.println("aaabaaa - " + solution.longestPalindrome("aaabaaaa"));
    System.out.println("ccc - " + solution.longestPalindrome("ccc"));
    System.out.println("a - " + solution.longestPalindrome("abcda"));
    System.out.println("abcba - " + solution.longestPalindrome("abcba"));
    System.out.println("a - " + solution.longestPalindrome("ac"));
    System.out.println("bab - " + solution.longestPalindrome("babad"));
    System.out.println("bb  - " + solution.longestPalindrome("cbbd"));
    System.out.println("bb  - " + solution.longestPalindrome("abbc"));
    System.out.println("a - " + solution.longestPalindrome("a"));
  }
}

6. ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 6. ZigZag Conversion
 *
 * https://leetcode.com/problems/zigzag-conversion/[ZigZag Conversion - LeetCode]
 *
 * The string `"PAYPALISHIRING"` is written in a zigzag pattern on a given number
 * of rows like this: (you may want to display this pattern in a fixed font for
 * better legibility)
 *
 * [source]
 * ----
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 * ----
 *
 * And then read line by line: `"PAHNAPLSIIGYIR"`
 *
 * Write the code that will take a string and make this conversion given a number of rows:
 *
 * [source]
 * ----
 * string convert(string s, int numRows);
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input: s = "PAYPALISHIRING", numRows = 3
 * Output: "PAHNAPLSIIGYIR"
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: s = "PAYPALISHIRING", numRows = 4
 * Output: "PINALSIGYAHRPI"
 * Explanation:
 *
 * P     I    N
 * A   L S  I G
 * Y A   H R
 * P     I
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-14 18:20
 */
public class _0006_ZigZagConversion {
    /**
     * Runtime: 5 ms, faster than 73.81% of Java online submissions for ZigZag Conversion.
     *
     * Memory Usage: 38.7 MB, less than 77.68% of Java online submissions for ZigZag Conversion.
     */
    public String convert(String s, int numRows) {
        if (Objects.isNull(s) || s.length() == 0) {
            return "";
        }
        if (numRows == 1) {
            return s;
        }
        int length = s.length();
        int columnLength = length / numRows;

        StringBuilder[] builders = new StringBuilder[numRows];
        for (int i = 0; i < builders.length; i++) {
            builders[i] = new StringBuilder(columnLength);
        }

        int direction = 1;
        int selector = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (selector == 0) {
                direction = 1;
            }
            if (selector == numRows - 1) {
                direction = -1;
            }
            char aChar = chars[i];
            builders[selector].append(aChar);
            selector += direction;
        }

        StringBuilder result = new StringBuilder(length);
        for (StringBuilder builder : builders) {
            result.append(builder);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        _0006_ZigZagConversion solution = new _0006_ZigZagConversion();

        String example3 = solution.convert("AB", 1);
        System.out.println(example3 + " " + "AB".equals(example3));

        String example1 = solution.convert("PAYPALISHIRING", 3);
        System.out.println(example1 + " " + "PAHNAPLSIIGYIR".equals(example1));

        String example2 = solution.convert("PAYPALISHIRING", 4);
        System.out.println(example2 + " " + "PINALSIGYAHRPI".equals(example2));
    }
}

7. Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21

Note:

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-231, 231- 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题分析

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * = 7. Reverse Integer
 *
 * https://leetcode.com/problems/reverse-integer/description/[Reverse Integer - LeetCode]
 *
 * Given a 32-bit signed integer, reverse digits of an integer.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 123
 * Output: 321
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: -123
 * Output: -321
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 120
 * Output: 21
 * ----
 *
 * == Note
 *
 * Assume we are dealing with an environment which could only store integers
 * within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of
 * this problem, assume that your function returns 0 when the reversed integer overflows.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-01
 */
public class _0007_ReverseInteger {
  public static int reverse(int x) {
    int sign = 1;
    if (x < 0) {
      sign = -1;
      if (x < -Integer.MAX_VALUE) {
        return 0;
      }
      x = -x;
    }
    int result = 0;
    while (x > 0) {
      int digit = x % 10;
      int num = result * 10 + digit;
      if ((num - digit) / 10 != result) {
        return 0;
      }
      result = num;

      x /= 10;
    }
    return sign * result;
  }

  public static int reverse1(int x) {
    if (x == 0
      || x > Math.pow(2, 31)
      || x < -Math.pow(2, 31)) {
      return 0;
    }

    int sign = 1;
    int positiveNum = x;
    if (x < 0) {
      sign = -1;
      positiveNum = x * sign;
    }

    boolean zeroOfEnd = true;
    List<Integer> bitNums = new ArrayList<>(25);
    for (int i = positiveNum; i > 0; ) {
      int bitNum = i % 10;
      i = i / 10;
      if (zeroOfEnd && bitNum == 0) {
        continue;
      }
      bitNums.add(bitNum);
      if (zeroOfEnd) {
        zeroOfEnd = false;
      }
    }

    long result = 0;
    for (int j = 0; j < bitNums.size(); j++) {
      result += bitNums.get(j) * ((long) Math.pow(10, bitNums.size() - j - 1));
    }
    if (result > Integer.MAX_VALUE) {
      return 0;
    }

    return (int) result * sign;
  }

  public static void main(String[] args) {
    System.out.println(reverse(120));
    System.out.println(reverse(123));
    System.out.println(reverse(-123));
    System.out.println(reverse(-10305));
    int i = 1534236469;
    System.out.println(reverse(i));
    System.out.println(Integer.bitCount(i));
    System.out.println(i);
    System.out.println(reverse(Integer.MAX_VALUE));
    System.out.println(reverse(Integer.MIN_VALUE));
  }
}

8. String to Integer (atoi)

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

  • Only the space character ' ' is considered as whitespace character.

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-231, 231- 1]. If the numerical value is out of the range of representable values, INT_MAX (231- 1) or INT_MIN (-231) is returned.

Example 1:
Input: "42"
Output: 42
Example 2:
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (-231) is returned.

解题分析

result > (Integer.MAX_VALUE - num) / 10 注意这个判断移除方法。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 8. String to Integer (atoi)
 *
 * https://leetcode.com/problems/string-to-integer-atoi/[String to Integer (atoi) - LeetCode]
 *
 * Implement atoi which converts a string to an integer.
 *
 * The function first discards as many whitespace characters as necessary until the first
 * non-whitespace character is found. Then, starting from this character, takes an optional
 * initial plus or minus sign followed by as many numerical digits as possible, and interprets
 * them as a numerical value.
 *
 * The string can contain additional characters after those that form the integral number,
 * which are ignored and have no effect on the behavior of this function.
 *
 * If the first sequence of non-whitespace characters in str is not a valid integral number,
 * or if no such sequence exists because either str is empty or it contains only whitespace characters,
 * no conversion is performed.
 *
 * If no valid conversion could be performed, a zero value is returned.
 *
 * Note::
 * * Only the space character `' '` is considered as whitespace character.
 * * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "42"
 * Output: 42
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "   -42"
 * Output: -42
 * Explanation: The first non-whitespace character is '-', which is the minus sign.
 * Then take as many numerical digits as possible, which gets 42.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: "4193 with words"
 * Output: 4193
 * Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: "words and 987"
 * Output: 0
 * Explanation: The first non-whitespace character is 'w', which is not a numerical
 * digit or a +/- sign. Therefore no valid conversion could be performed.
 * ----
 *
 * .Example 5:
 * [source]
 * ----
 * Input: "-91283472332"
 * Output: -2147483648
 * Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
 * Thefore INT_MIN (−231) is returned.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-14 19:57
 */
public class _0008_StringToIntegerAtoi {

  public int myAtoi(String str) {
    char[] chars = str.toCharArray();
    int n = str.length();
    int idx = 0;
    // 除去前面的空白符
    while (idx < n && Character.isWhitespace(chars[idx])) {
      idx++;
    }
    if (idx == n) {
      return 0;
    }
    // 判断正负号
    boolean negative = false;
    if (chars[idx] == '-') {
      negative = true;
      idx++;
    } else if (chars[idx] == '+') {
      // negative = false;
      idx++;
    } else if (!Character.isDigit(chars[idx])) {
      return 0;
    }
    // 计算数字
    int result = 0;
    while (idx < n && Character.isDigit(chars[idx])) {
      int num = chars[idx] - '0';
      // 注意这个判断是否溢出的方式。
      if (result > (Integer.MAX_VALUE - num) / 10) {
        return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
      }
      result = result * 10 + num;
      idx++;
    }
    return negative ? -result : result;
  }

  /**
   * Runtime: 1 ms, faster than 100.00% of Java online submissions for String to Integer (atoi).
   *
   * Memory Usage: 35.8 MB, less than 99.90% of Java online submissions for String to Integer (atoi).
   */
  public int myAtoi2(String str) {
    int result = 0;
    if (Objects.isNull(str) || str.length() == 0) {
      return result;
    }

    int index = 0;
    int length = str.length();
    while (index < length && str.charAt(index) == ' ') {
      index++;
    }

    int sign = 1;
    if (index < length && isSign(str.charAt(index))) {
      if (str.charAt(index) == '-') {
        sign = -1;
      }
      index++;
    }

    int decimals = 10;
    while (index < length && isNumber(str.charAt(index))) {
      int number = str.charAt(index) - '0';

      if (result > Integer.MAX_VALUE / 10
        || (result == Integer.MAX_VALUE / 10 && number > Integer.MAX_VALUE % 10)) {
        return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
      }

      result = result * decimals + number;

      index++;
    }

    return result * sign;
  }

  private boolean isNumber(char aChar) {
    return '0' <= aChar && aChar <= '9';
  }

  private boolean isSign(char aChar) {
    return aChar == '-' || aChar == '+';
  }

  public int myAtoiD2u(String str) {
    long result = 0;
    if (Objects.isNull(str) || str.length() == 0) {
      return (int) result;
    }
    char[] chars = str.toCharArray();
    int start = -1;
    int end = -1;
    int signed = 1;
    boolean hasSigned = false;
    boolean isStarted = false;
    boolean firstIsZero = true;
    for (int i = 0; i < chars.length; i++) {
      char aChar = chars[i];
      if (isStarted && !isNumber(aChar)) {
        break;
      }
      if (aChar == ' ') {
        start++;
        continue;
      }
      if (!isNumber(aChar) && !isSign(aChar)) {
        return (int) result;
      }
      if (isSign(aChar) && !hasSigned) {
        if (aChar == '-') {
          signed = -1;
        }
        hasSigned = true;
        isStarted = true;
        continue;
      }
      isStarted = true;
      if (firstIsZero && aChar == '0') {
        continue;
      }
      if (isStarted && !isNumber(aChar)) {
        break;
      }
      if (firstIsZero && aChar != '0' && isNumber(aChar)) {
        firstIsZero = false;
        start = i;
        end = i;
      }
      if (isNumber(aChar)) {
        end = i;
      } else {
        break;
      }
    }

    for (int i = end; chars.length > i && i >= start && start >= 0; i--) {
      char aChar = chars[i];
      long base = pow(10, end - i);
      if (base > Integer.MAX_VALUE) {
        if (signed == 1) {
          return Integer.MAX_VALUE;
        } else {
          return Integer.MIN_VALUE;
        }
      }
      if ('0' == aChar || isSign(aChar)) {
        continue;
      }
      if (!isNumber(aChar)) {
        break;
      }
      long newResult = (long) (aChar - '0') * base + result;
      boolean isOutOfRange = (signed > 0 && newResult > Integer.MAX_VALUE)
        || (signed < 0 && newResult * signed < Integer.MIN_VALUE);
      if (isOutOfRange) {
        if (signed == 1) {
          return Integer.MAX_VALUE;
        } else {
          return Integer.MIN_VALUE;
        }
      }
      result = newResult;
    }

    result *= signed;

    return (int) result;
  }

  private long pow(int base, int exponent) {
    long result = 1L;
    for (int i = 0; i < exponent; i++) {
      result *= base;
    }
    return result;
  }

  public static void main(String[] args) {
    _0008_StringToIntegerAtoi solution = new _0008_StringToIntegerAtoi();

    int i17 = solution.myAtoi("-2147483647");
    System.out.println(i17 + " : " + (-2147483647 == i17));

    int i16 = solution.myAtoi("-2147483649");
    System.out.println(i16 + " : " + (-2147483648 == i16));

    int i15 = solution.myAtoi(Integer.toString(Integer.MIN_VALUE));
    System.out.println(i15 + " : " + (-2147483648 == i15));

    int i14 = solution.myAtoi("2147483646");
    System.out.println(i14 + " : " + (2147483646 == i14));

    int i13 = solution.myAtoi("0-1");
    System.out.println(i13 + " : " + (0 == i13));

    int i12 = solution.myAtoi("    0000000000000   ");
    System.out.println(i12 + " : " + (0 == i12));

    int i11 = solution.myAtoi("  0000000000012345678");
    System.out.println(i11 + " : " + (12345678 == i11));

    int i10 = solution.myAtoi("10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000522545459");
    System.out.println(i10 + " : " + (Integer.MAX_VALUE == i10));

    int i9 = solution.myAtoi("-abc");
    System.out.println(i9 + " : " + (0 == i9));

    int i8 = solution.myAtoi("20000000000000000000");
    System.out.println(i8 + " : " + (Integer.MAX_VALUE == i8));

    int i7 = solution.myAtoi("-6147483648");
    System.out.println(i7 + " : " + (Integer.MIN_VALUE == i7));

    int i6 = solution.myAtoi("+");
    System.out.println(i6 + " : " + (0 == i6));

    int i3 = solution.myAtoi("4193 with words");
    System.out.println(i3 + " : " + (4193 == i3));

    int i2 = solution.myAtoi("   -42");
    System.out.println(i2 + " : " + (-42 == i2));

    int i1 = solution.myAtoi("42");
    System.out.println(i1 + " : " + (42 == i1));

    int i4 = solution.myAtoi("words and 987");
    System.out.println(i4 + " : " + (0 == i4));

    int i5 = solution.myAtoi("-91283472332");
    System.out.println(i5 + " : " + (-2147483648 == i5));
  }
}

9. Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

解题分析

如果是回文数字,则反转之后数字相等。可以再进一步,不需要完全反转,只需要反转一半即可,反转一般,反转数字跟原始数字就相等或者相近了。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * = 9. Palindrome Number
 *
 * https://leetcode.com/problems/palindrome-number/description/[Palindrome Number - LeetCode]
 *
 * Determine whether an integer is a palindrome. An integer is a palindrome when
 * it reads the same backward as forward.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 121
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: -121
 * Output: false
 * Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 10
 * Output: false
 * Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
 * ----
 *
 * == Follow up
 *
 * Coud you solve it without converting the integer to a string?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-01
 */
public class _0009_PalindromeNumber {

  public static boolean isPalindrome(int x) {
    if (x < 0 || (x > 0 && x % 10 == 0)) {
      return false;
    }
    // 如果是回文数字,则反转之后数字相等。
    // 可以再进一步,不需要完全反转,只需要反转一半即可。
    int part = 0;
    while (x > part) {
      int digit = x % 10;
      part = part * 10 + digit;
      x /= 10;
    }
    // 这里分分两种情况:
    // abccba 型,则 x == part == abc
    // abcba  型,则 x == 12, part = abc,所以 x == part / 10
    return x == part || x == part / 10;
  }

  public static boolean isPalindromeDigits(int x) {
    boolean result = true;
    if (x < 0) {
      return false;
    }
    int multiBitNumStarter = 10;
    if (x < multiBitNumStarter) {
      return result;
    }
    List<Integer> bitNums = new ArrayList<>(25);
    for (int i = x; i > 0; i /= 10) {
      bitNums.add(i % 10);
    }
    int halfLength = bitNums.size() / 2;
    for (int i = 0; i < halfLength; i++) {
      if (!bitNums.get(i).equals(bitNums.get(bitNums.size() - i - 1))) {
        result = false;
        break;
      }
    }

    return result;
  }

  public static void main(String[] args) {
    System.out.println(isPalindrome(121));
    System.out.println(isPalindrome(-121));
    System.out.println(isPalindrome(10));
  }
}

10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.

  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = "."
*Output: true
Explanation: "." means "zero or more () of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.diguage.algorithm.leetcode;

/**
 * = 10. Regular Expression Matching
 *
 * https://leetcode.com/problems/regular-expression-matching/[Regular Expression Matching - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-26 18:56
 */
public class _0010_RegularExpressionMatching {
    // TODO Hard
}

11. Container With Most Water

Given n non-negative integers a1, a2, …​, a~n ~, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

*Note: *You may not slant the container and n is at least 2.

question 11

[.small]#The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. #

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解题分析

双指针左右夹逼,保留高个,移动低个。

这里有个疑问,不考虑中间

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.diguage.algorithm.leetcode;

/**
 * = 11. Container With Most Water
 *
 * https://leetcode.com/problems/container-with-most-water/description/[Container With Most Water - LeetCode]
 *
 * Given n non-negative integers a1, a2, ..., an, where each represents a point
 * at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
 * of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis
 * forms a container, such that the container contains the most water.
 *
 * Note: You may not slant the container and n is at least 2.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-13
 */
public class _0011_ContainerWithMostWater {
  public static int maxArea(int[] height) {
    int result = 0;
    int left = 0, right = height.length - 1;
    while (left < right) {
      int area = Math.min(height[left], height[right]) * (right - left);
      result = Math.max(result, area);
      if (height[left] < height[right]) {
        left++;
      } else {
        right--;
      }
    }
    return result;
  }

  public static void main(String[] args) {
    int[] height = new int[]{3, 8, 4, 7, 5, 9, 1, 2, 6};
    System.out.println(maxArea(height));
  }
}

12. Integer to Roman

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.

  • X can be placed before L (50) and C (100) to make 40 and 90.

  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 12. Integer to Roman
 *
 * https://leetcode.com/problems/integer-to-roman/[Integer to Roman - LeetCode]
 *
 * Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
 *
 * [source]
 * ----
 * Symbol       Value
 * I             1
 * V             5
 * X             10
 * L             50
 * C             100
 * D             500
 * M             1000
 * ----
 *
 * For example, two is written as `II` in Roman numeral, just two one's added together.
 * Twelve is written as, `XII`, which is simply `X` + `II`. The number twenty seven is
 * written as XXVII, which is `XX` + `V` + `II`.
 *
 * Roman numerals are usually written largest to smallest from left to right. However,
 * the numeral for four is not `IIII`. Instead, the number four is written as `IV`.
 * Because the one is before the five we subtract it making four. The same principle
 * applies to the number nine, which is written as `IX`. There are six instances
 * where subtraction is used:
 *
 * * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9.
 * * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90.
 * * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900.
 *
 * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 3
 * Output: "III"
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 4
 * Output: "IV"
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 9
 * Output: "IX"
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: 58
 * Output: "LVIII"
 * Explanation: L = 50, V= 5, III = 3.
 * ----
 *
 * .Example 5:
 * [source]
 * ----
 * Input: 1994
 * Output: "MCMXCIV"
 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-17 10:45
 */
public class _0012_IntegerToRoman {
    /**
     * Runtime: 46 ms, faster than 5.34% of Java online submissions for Integer to Roman.
     *
     * Memory Usage: 44.1 MB, less than 5.01% of Java online submissions for Integer to Roman.
     *
     * @since 2019-07-17 11:24:02
     */
    public String intToRoman(int num) {
        Map<Integer, String> i2r = new HashMap<>(19);
        i2r.put(1, "I");
        i2r.put(5, "V");
        i2r.put(10, "X");
        i2r.put(50, "L");
        i2r.put(100, "C");
        i2r.put(500, "D");
        i2r.put(1000, "M");
        i2r.put(4, "IV");
        i2r.put(9, "IX");
        i2r.put(40, "XL");
        i2r.put(90, "XC");
        i2r.put(400, "CD");
        i2r.put(900, "CM");

        StringBuilder builder = new StringBuilder(20);

        int size = i2r.size();
        int temp = num;

        Integer[] keys = i2r.keySet().toArray(new Integer[0]);
        Arrays.sort(keys, Comparator.comparingInt(a -> -a));

        int lastIndex = 0;
        while (temp > 0) {
            for (int i = lastIndex; i < size; i++) {
                Integer key = keys[i];
                if (temp >= key) {
                    lastIndex = i;
                    temp -= key;
                    builder.append(i2r.get(key));
                    break;
                }
            }
        }

        return builder.toString();
    }

    public static void main(String[] args) {
        _0012_IntegerToRoman solution = new _0012_IntegerToRoman();

        String roman5 = solution.intToRoman(1994);
        System.out.println("MCMXCIV".equals(roman5) + " : " + roman5);


        String roman = solution.intToRoman(3);
        System.out.println("III".equals(roman) + " : " + roman);

        String roman2 = solution.intToRoman(4);
        System.out.println("IV".equals(roman2) + " : " + roman2);

        String roman3 = solution.intToRoman(9);
        System.out.println("IX".equals(roman3) + " : " + roman3);

        String roman4 = solution.intToRoman(58);
        System.out.println("LVIII".equals(roman4) + " : " + roman4);
    }
}

13. Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.

  • X can be placed before L (50) and C (100) to make 40 and 90.

  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

解题分析

查看罗马数字,如果左边的数字比右边大,则就是需要做减法,否则做加法。

0013 0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Objects;

/**
 * = 13. Roman to Integer
 *
 * https://leetcode.com/problems/roman-to-integer/[Roman to Integer - LeetCode]
 *
 * Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
 *
 * [source]
 * ----
 * Symbol       Value
 * I             1
 * V             5
 * X             10
 * L             50
 * C             100
 * D             500
 * M             1000
 * ----
 *
 * For example, two is written as `II` in Roman numeral, just two one's added together.
 * Twelve is written as, `XII`, which is simply `X` + `II`. The number twenty seven is
 * written as XXVII, which is `XX` + `V` + `II`.
 *
 * Roman numerals are usually written largest to smallest from left to right. However,
 * the numeral for four is not `IIII`. Instead, the number four is written as `IV`.
 * Because the one is before the five we subtract it making four. The same principle
 * applies to the number nine, which is written as `IX`. There are six instances
 * where subtraction is used:
 *
 * * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9.
 * * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90.
 * * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900.
 *
 * Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "III"
 * Output: 3
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "IV"
 * Output: 4
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: "IX"
 * Output: 9
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: "LVIII"
 * Output: 58
 * Explanation: L = 50, V= 5, III = 3.
 * ----
 *
 * .Example 5:
 * [source]
 * ----
 * Input: "MCMXCIV"
 * Output: 1994
 * Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-11 17:14
 */
public class _0013_RomanToInteger {

  // 从右向左,从小到大,更容易理解
  public int romanToInt(String s) {
    int result = 0;
    int pre = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
      int curr = charToNum(s.charAt(i));
      if (curr >= pre) {
        result += curr;
      } else {
        result -= curr;
      }
      pre = curr;
    }
    return result;
  }

  private int charToNum(char c) {
    switch (c) {
      case 'I': return 1;
      case 'V': return 5;
      case 'X': return 10;
      case 'L': return 50;
      case 'C': return 100;
      case 'D': return 500;
      case 'M': return 1000;
      default: return 0;
    }
  }

  // 从左向右处理
  public int romanToIntLeftToRight(String s) {
    int result = 0;
    int prenum = charToNum(s.charAt(0));
    for (int i = 1; i < s.length(); i++) {
      int num = charToNum(s.charAt(i));
      if (prenum < num) {
        result -= prenum;
      } else {
        result += prenum;
      }
      prenum = num;
    }
    result += prenum;
    return result;
  }

  public int romanToInt2(String s) {
    int result = 0;
    if (Objects.isNull(s) || s.length() == 0) {
      return result;
    }

    HashMap<String, Integer> r2i = new HashMap<>();
    r2i.put("I", 1);
    r2i.put("V", 5);
    r2i.put("X", 10);
    r2i.put("L", 50);
    r2i.put("C", 100);
    r2i.put("D", 500);
    r2i.put("M", 1000);
    r2i.put("IV", 4);
    r2i.put("IX", 9);
    r2i.put("XL", 40);
    r2i.put("XC", 90);
    r2i.put("CD", 400);
    r2i.put("CM", 900);

    for (int i = s.length(); i > 0; ) {
      int step = 2;
      int beginIndex = i - step;
      if (beginIndex < 0) {
        beginIndex = 0;
      }
      String symbol = s.substring(beginIndex, i);
      Integer value = r2i.get(symbol);
      if (Objects.isNull(value)) {
        step = 1;
        beginIndex = i - step;
        if (beginIndex < 0) {
          beginIndex = 0;
        }
        symbol = s.substring(beginIndex, i);
        value = r2i.get(symbol);
      }
      result += value;
      i -= step;
    }
    return result;
  }

  public static void main(String[] args) {
    _0013_RomanToInteger roman = new _0013_RomanToInteger();
    System.out.println(roman.romanToInt("III") == 3);
    System.out.println(roman.romanToInt("IV") == 4);
    System.out.println(roman.romanToInt("IX") == 9);
    System.out.println(roman.romanToInt("LVIII") == 58);
    System.out.println(roman.romanToInt("MCMXCIV") == 1994);
  }
}

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 14. Longest Common Prefix
 *
 * https://leetcode.com/problems/longest-common-prefix/[Longest Common Prefix - LeetCode]
 *
 * Write a function to find the longest common prefix string amongst an array of strings.
 *
 * If there is no common prefix, return an empty string "".
 *
 * .Example 1:
 * [source]
 * ----
 * Input: ["flower","flow","flight"]
 * Output: "fl"
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: ["dog","racecar","car"]
 * Output: ""
 * Explanation: There is no common prefix among the input strings.
 * ----
 *
 * *Note:*
 *
 * All given inputs are in lowercase letters `a-z`.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-11 17:50
 */
public class _0014_LongestCommonPrefix {

  /**
   * 使用逐列扫描前进,遇到不同时,则终止。
   */
  public String longestCommonPrefix(String[] strs) {
    if (Objects.isNull(strs) || strs.length == 0) {
      return "";
    }
    for (int i = 0; i < strs[0].length(); i++) {
      char c = strs[0].charAt(i);
      for (int j = 1; j < strs.length; j++) {
        if (i == strs[j].length() || strs[j].charAt(i) != c) {
          return strs[0].substring(0, i);
        }
      }
    }
    return strs[0];
  }

  public String longestCommonPrefix2(String[] strs) {
    if (Objects.isNull(strs) || strs.length == 0) {
      return "";
    }
    if (strs.length == 1) {
      return strs[0];
    }
    int maxLength = Integer.MAX_VALUE;
    for (String str : strs) {
      int strLength = str.length();
      if (strLength < maxLength) {
        maxLength = strLength;
      }
    }

    int length = 0;

    loop:
    while (length < maxLength) {
      char aChar = strs[0].charAt(length);
      for (int i = 1; i < strs.length; i++) {
        char bChar = strs[i].charAt(length);
        if (aChar != bChar) {
          break loop;
        }
      }
      length += 1;
    }
    if (length > 0) {
      return strs[0].substring(0, length);
    } else {
      return "";
    }
  }

  public static void main(String[] args) {
    _0014_LongestCommonPrefix prefix = new _0014_LongestCommonPrefix();
    String prefix1 = prefix.longestCommonPrefix(new String[]{"flower", "flow", "flight"});
    System.out.println("fl".equals(prefix1) + " " + prefix1);
    System.out.println("".equals(prefix.longestCommonPrefix(new String[]{"dog", "racecar", "car"})));
  }
}

15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解题分析

为什么参考资料中,JS 的代码可以通过,但是转成 Java 之后就不能通过呢?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
package com.diguage.algorithm.leetcode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * = 15. 3Sum
 *
 * https://leetcode.com/problems/3sum/description/[3Sum - LeetCode]
 *
 * Given an array `nums` of n integers, are there elements `a`, `b`, `c` in
 * `nums` such that `a + b + c = 0`? Find all unique triplets in the array
 * which gives the sum of zero.
 *
 * == Note
 *
 * The solution set must not contain duplicate triplets.
 *
 * .Example:
 * [source]
 * ----
 * Given array nums = [-1, 0, 1, 2, -1, -4],
 *
 * A solution set is:
 * [
 *   [-1, 0, 1],
 *   [-1, -1, 2]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-19
 */
public class _0015_3Sum {
  // TODO 还没有通过
  public static List<List<Integer>> threeSum(int[] nums) {
    if (Objects.isNull(nums) || nums.length < 3) {
      return Collections.emptyList();
    }
    List<List<Integer>> result = new ArrayList<>();
    Arrays.sort(nums);
    if (nums[0] * nums[nums.length - 1] > 0) {
      return result;
    }
    for (int i = 0; i < nums.length - 2 && nums[i] <= 0; ) {
      int left = i + 1, right = nums.length - 1;
      while (left < right && nums[i] * nums[right] <= 0) {
        int sum = nums[i] + nums[left] + nums[right];
        if (sum == 0) {
          result.add(Arrays.asList(nums[i], nums[left], nums[right]));
        }
        if (sum > 0) {
          while (left < right && nums[right] == nums[--right]) {}
        } else {
          while (left < right && nums[left] == nums[++left]) {}
        }
      }
      while (i < nums.length - 1 && nums[i] == nums[++i]) {}
    }
    return result;
  }

  public static List<List<Integer>> threeSum2(int[] nums) {
    if (nums.length < 3) {
      return new ArrayList<>();
    }
    Set<List<Integer>> result = new HashSet<>();

    Arrays.sort(nums);

    Map<Integer, Integer> numMap = new HashMap<>(nums.length * 4 / 3 + 1);
    for (int i = 0; i < nums.length; i++) {
      numMap.put(nums[i], i);
    }

    if (numMap.size() == 1 && numMap.keySet().contains(0)) {
      result.add(Arrays.asList(0, 0, 0));
      return new ArrayList<>(result);
    }

    for (int i = 0; i < nums.length; i++) {
      for (int j = nums.length - 1; j > i; j--) {
        int minuend = 0 - (nums[i] + nums[j]);
        if (numMap.containsKey(minuend)) {
          Integer k = numMap.get(minuend);
          if (i != k && j != k) {
            int[] oneResult = new int[]{nums[i], nums[j], minuend};
            Arrays.sort(oneResult);
            result.add(Arrays.stream(oneResult).boxed().collect(Collectors.toList()));
          }
        }
      }
    }

    return new ArrayList<>(result);
  }

  public static void main(String[] args) {
//        int[] nums = {-1, 0, 1, 2, -1, -4};
    int[] nums = {82597, -9243, 62390, 83030, -97960, -26521, -61011, 83390, -38677, 12333, 75987, 46091, 83794, 19355, -71037, -6242, -28801, 324, 1202, -90885, -2989, -95597, -34333, 35528, 5680, 89093, -90606, 50360, -29393, -27012, 53313, 65213, 99818, -82405, -41661, -3333, -51952, 72135, -1523, 26377, 74685, 96992, 92263, 15929, 5467, -99555, -43348, -41689, -60383, -3990, 32165, 65265, -72973, -58372, 12741, -48568, -46596, 72419, -1859, 34153, 62937, 81310, -61823, -96770, -54944, 8845, -91184, 24208, -29078, 31495, 65258, 14198, 85395, 70506, -40908, 56740, -12228, -40072, 32429, 93001, 68445, -73927, 25731, -91859, -24150, 10093, -60271, -81683, -18126, 51055, 48189, -6468, 25057, 81194, -58628, 74042, 66158, -14452, -49851, -43667, 11092, 39189, -17025, -79173, 13606, 83172, 92647, -59741, 19343, -26644, -57607, 82908, -20655, 1637, 80060, 98994, 39331, -31274, -61523, 91225, -72953, 13211, -75116, -98421, -41571, -69074, 99587, 39345, 42151, -2460, 98236, 15690, -52507, -95803, -48935, -46492, -45606, -79254, -99851, 52533, 73486, 39948, -7240, 71815, -585, -96252, 90990, -93815, 93340, -71848, 58733, -14859, -83082, -75794, -82082, -24871, -15206, 91207, -56469, -93618, 67131, -8682, 75719, 87429, -98757, -7535, -24890, -94160, 85003, 33928, 75538, 97456, -66424, -60074, -8527, -28697, -22308, 2246, -70134, -82319, -10184, 87081, -34949, -28645, -47352, -83966, -60418, -15293, -53067, -25921, 55172, 75064, 95859, 48049, 34311, -86931, -38586, 33686, -36714, 96922, 76713, -22165, -80585, -34503, -44516, 39217, -28457, 47227, -94036, 43457, 24626, -87359, 26898, -70819, 30528, -32397, -69486, 84912, -1187, -98986, -32958, 4280, -79129, -65604, 9344, 58964, 50584, 71128, -55480, 24986, 15086, -62360, -42977, -49482, -77256, -36895, -74818, 20, 3063, -49426, 28152, -97329, 6086, 86035, -88743, 35241, 44249, 19927, -10660, 89404, 24179, -26621, -6511, 57745, -28750, 96340, -97160, -97822, -49979, 52307, 79462, 94273, -24808, 77104, 9255, -83057, 77655, 21361, 55956, -9096, 48599, -40490, -55107, 2689, 29608, 20497, 66834, -34678, 23553, -81400, -66630, -96321, -34499, -12957, -20564, 25610, -4322, -58462, 20801, 53700, 71527, 24669, -54534, 57879, -3221, 33636, 3900, 97832, -27688, -98715, 5992, 24520, -55401, -57613, -69926, 57377, -77610, 20123, 52174, 860, 60429, -91994, -62403, -6218, -90610, -37263, -15052, 62069, -96465, 44254, 89892, -3406, 19121, -41842, -87783, -64125, -56120, 73904, -22797, -58118, -4866, 5356, 75318, 46119, 21276, -19246, -9241, -97425, 57333, -15802, 93149, 25689, -5532, 95716, 39209, -87672, -29470, -16324, -15331, 27632, -39454, 56530, -16000, 29853, 46475, 78242, -46602, 83192, -73440, -15816, 50964, -36601, 89758, 38375, -40007, -36675, -94030, 67576, 46811, -64919, 45595, 76530, 40398, 35845, 41791, 67697, -30439, -82944, 63115, 33447, -36046, -50122, -34789, 43003, -78947, -38763, -89210, 32756, -20389, -31358, -90526, -81607, 88741, 86643, 98422, 47389, -75189, 13091, 95993, -15501, 94260, -25584, -1483, -67261, -70753, 25160, 89614, -90620, -48542, 83889, -12388, -9642, -37043, -67663, 28794, -8801, 13621, 12241, 55379, 84290, 21692, -95906, -85617, -17341, -63767, 80183, -4942, -51478, 30997, -13658, 8838, 17452, -82869, -39897, 68449, 31964, 98158, -49489, 62283, -62209, -92792, -59342, 55146, -38533, 20496, 62667, 62593, 36095, -12470, 5453, -50451, 74716, -17902, 3302, -16760, -71642, -34819, 96459, -72860, 21638, 47342, -69897, -40180, 44466, 76496, 84659, 13848, -91600, -90887, -63742, -2156, -84981, -99280, 94326, -33854, 92029, -50811, 98711, -36459, -75555, 79110, -88164, -97397, -84217, 97457, 64387, 30513, -53190, -83215, 252, 2344, -27177, -92945, -89010, 82662, -11670, 86069, 53417, 42702, 97082, 3695, -14530, -46334, 17910, 77999, 28009, -12374, 15498, -46941, 97088, -35030, 95040, 92095, -59469, -24761, 46491, 67357, -66658, 37446, -65130, -50416, 99197, 30925, 27308, 54122, -44719, 12582, -99525, -38446, -69050, -22352, 94757, -56062, 33684, -40199, -46399, 96842, -50881, -22380, -65021, 40582, 53623, -76034, 77018, -97074, -84838, -22953, -74205, 79715, -33920, -35794, -91369, 73421, -82492, 63680, -14915, -33295, 37145, 76852, -69442, 60125, -74166, 74308, -1900, -30195, -16267, -60781, -27760, 5852, 38917, 25742, -3765, 49097, -63541, 98612, -92865, -30248, 9612, -8798, 53262, 95781, -42278, -36529, 7252, -27394, -5021, 59178, 80934, -48480, -75131, -54439, -19145, -48140, 98457, -6601, -51616, -89730, 78028, 32083, -48904, 16822, -81153, -8832, 48720, -80728, -45133, -86647, -4259, -40453, 2590, 28613, 50523, -4105, -27790, -74579, -17223, 63721, 33489, -47921, 97628, -97691, -14782, -65644, 18008, -93651, -71266, 80990, -76732, -47104, 35368, 28632, 59818, -86269, -89753, 34557, -92230, -5933, -3487, -73557, -13174, -43981, -43630, -55171, 30254, -83710, -99583, -13500, 71787, 5017, -25117, -78586, 86941, -3251, -23867, -36315, 75973, 86272, -45575, 77462, -98836, -10859, 70168, -32971, -38739, -12761, 93410, 14014, -30706, -77356, -85965, -62316, 63918, -59914, -64088, 1591, -10957, 38004, 15129, -83602, -51791, 34381, -89382, -26056, 8942, 5465, 71458, -73805, -87445, -19921, -80784, 69150, -34168, 28301, -68955, 18041, 6059, 82342, 9947, 39795, 44047, -57313, 48569, 81936, -2863, -80932, 32976, -86454, -84207, 33033, 32867, 9104, -16580, -25727, 80157, -70169, 53741, 86522, 84651, 68480, 84018, 61932, 7332, -61322, -69663, 76370, 41206, 12326, -34689, 17016, 82975, -23386, 39417, 72793, 44774, -96259, 3213, 79952, 29265, -61492, -49337, 14162, 65886, 3342, -41622, -62659, -90402, -24751, 88511, 54739, -21383, -40161, -96610, -24944, -602, -76842, -21856, 69964, 43994, -15121, -85530, 12718, 13170, -13547, 69222, 62417, -75305, -81446, -38786, -52075, -23110, 97681, -82800, -53178, 11474, 35857, 94197, -58148, -23689, 32506, 92154, -64536, -73930, -77138, 97446, -83459, 70963, 22452, 68472, -3728, -25059, -49405, 95129, -6167, 12808, 99918, 30113, -12641, -26665, 86362, -33505, 50661, 26714, 33701, 89012, -91540, 40517, -12716, -57185, -87230, 29914, -59560, 13200, -72723, 58272, 23913, -45586, -96593, -26265, -2141, 31087, 81399, 92511, -34049, 20577, 2803, 26003, 8940, 42117, 40887, -82715, 38269, 40969, -50022, 72088, 21291, -67280, -16523, 90535, 18669, 94342, -39568, -88080, -99486, -20716, 23108, -28037, 63342, 36863, -29420, -44016, 75135, 73415, 16059, -4899, 86893, 43136, -7041, 33483, -67612, 25327, 40830, 6184, 61805, 4247, 81119, -22854, -26104, -63466, 63093, -63685, 60369, 51023, 51644, -16350, 74438, -83514, 99083, 10079, -58451, -79621, 48471, 67131, -86940, 99093, 11855, -22272, -67683, -44371, 9541, 18123, 37766, -70922, 80385, -57513, -76021, -47890, 36154, 72935, 84387, -92681, -88303, -7810, 59902, -90, -64704, -28396, -66403, 8860, 13343, 33882, 85680, 7228, 28160, -14003, 54369, -58893, 92606, -63492, -10101, 64714, 58486, 29948, -44679, -22763, 10151, -56695, 4031, -18242, -36232, 86168, -14263, 9883, 47124, 47271, 92761, -24958, -73263, -79661, -69147, -18874, 29546, -92588, -85771, 26451, -86650, -43306, -59094, -47492, -34821, -91763, -47670, 33537, 22843, 67417, -759, 92159, 63075, 94065, -26988, 55276, 65903, 30414, -67129, -99508, -83092, -91493, -50426, 14349, -83216, -76090, 32742, -5306, -93310, -60750, -60620, -45484, -21108, -58341, -28048, -52803, 69735, 78906, 81649, 32565, -86804, -83202, -65688, -1760, 89707, 93322, -72750, 84134, 71900, -37720, 19450, -78018, 22001, -23604, 26276, -21498, 65892, -72117, -89834, -23867, 55817, -77963, 42518, 93123, -83916, 63260, -2243, -97108, 85442, -36775, 17984, -58810, 99664, -19082, 93075, -69329, 87061, 79713, 16296, 70996, 13483, -74582, 49900, -27669, -40562, 1209, -20572, 34660, 83193, 75579, 7344, 64925, 88361, 60969, 3114, 44611, -27445, 53049, -16085, -92851, -53306, 13859, -33532, 86622, -75666, -18159, -98256, 51875, -42251, -27977, -18080, 23772, 38160, 41779, 9147, 94175, 99905, -85755, 62535, -88412, -52038, -68171, 93255, -44684, -11242, -104, 31796, 62346, -54931, -55790, -70032, 46221, 56541, -91947, 90592, 93503, 4071, 20646, 4856, -63598, 15396, -50708, 32138, -85164, 38528, -89959, 53852, 57915, -42421, -88916, -75072, 67030, -29066, 49542, -71591, 61708, -53985, -43051, 28483, 46991, -83216, 80991, -46254, -48716, 39356, -8270, -47763, -34410, 874, -1186, -7049, 28846, 11276, 21960, -13304, -11433, -4913, 55754, 79616, 70423, -27523, 64803, 49277, 14906, -97401, -92390, 91075, 70736, 21971, -3303, 55333, -93996, 76538, 54603, -75899, 98801, 46887, 35041, 48302, -52318, 55439, 24574, 14079, -24889, 83440, 14961, 34312, -89260, -22293, -81271, -2586, -71059, -10640, -93095, -5453, -70041, 66543, 74012, -11662, -52477, -37597, -70919, 92971, -17452, -67306, -80418, 7225, -89296, 24296, 86547, 37154, -10696, 74436, -63959, 58860, 33590, -88925, -97814, -83664, 85484, -8385, -50879, 57729, -74728, -87852, -15524, -91120, 22062, 28134, 80917, 32026, 49707, -54252, -44319, -35139, 13777, 44660, 85274, 25043, 58781, -89035, -76274, 6364, -63625, 72855, 43242, -35033, 12820, -27460, 77372, -47578, -61162, -70758, -1343, -4159, 64935, 56024, -2151, 43770, 19758, -30186, -86040, 24666, -62332, -67542, 73180, -25821, -27826, -45504, -36858, -12041, 20017, -24066, -56625, -52097, -47239, -90694, 8959, 7712, -14258, -5860, 55349, 61808, -4423, -93703, 64681, -98641, -25222, 46999, -83831, -54714, 19997, -68477, 66073, 51801, -66491, 52061, -52866, 79907, -39736, -68331, 68937, 91464, 98892, 910, 93501, 31295, -85873, 27036, -57340, 50412, 21, -2445, 29471, 71317, 82093, -94823, -54458, -97410, 39560, -7628, 66452, 39701, 54029, 37906, 46773, 58296, 60370, -61090, 85501, -86874, 71443, -72702, -72047, 14848, 34102, 77975, -66294, -36576, 31349, 52493, -70833, -80287, 94435, 39745, -98291, 84524, -18942, 10236, 93448, 50846, 94023, -6939, 47999, 14740, 30165, 81048, 84935, -19177, -13594, 32289, 62628, -90612, -542, -66627, 64255, 71199, -83841, -82943, -73885, 8623, -67214, -9474, -35249, 62254, -14087, -90969, 21515, -83303, 94377, -91619, 19956, -98810, 96727, -91939, 29119, -85473, -82153, -69008, 44850, 74299, -76459, -86464, 8315, -49912, -28665, 59052, -69708, 76024, -92738, 50098, 18683, -91438, 18096, -19335, 35659, 91826, 15779, -73070, 67873, -12458, -71440, -46721, 54856, 97212, -81875, 35805, 36952, 68498, 81627, -34231, 81712, 27100, -9741, -82612, 18766, -36392, 2759, 41728, 69743, 26825, 48355, -17790, 17165, 56558, 3295, -24375, 55669, -16109, 24079, 73414, 48990, -11931, -78214, 90745, 19878, 35673, -15317, -89086, 94675, -92513, 88410, -93248, -19475, -74041, -19165, 32329, -26266, -46828, -18747, 45328, 8990, -78219, -25874, -74801, -44956, -54577, -29756, -99822, -35731, -18348, -68915, -83518, -53451, 95471, -2954, -13706, -8763, -21642, -37210, 16814, -60070, -42743, 27697, -36333, -42362, 11576, 85742, -82536, 68767, -56103, -63012, 71396, -78464, -68101, -15917, -11113, -3596, 77626, -60191, -30585, -73584, 6214, -84303, 18403, 23618, -15619, -89755, -59515, -59103, -74308, -63725, -29364, -52376, -96130, 70894, -12609, 50845, -2314, 42264, -70825, 64481, 55752, 4460, -68603, -88701, 4713, -50441, -51333, -77907, 97412, -66616, -49430, 60489, -85262, -97621, -18980, 44727, -69321, -57730, 66287, -92566, -64427, -14270, 11515, -92612, -87645, 61557, 24197, -81923, -39831, -10301, -23640, -76219, -68025, 92761, -76493, 68554, -77734, -95620, -11753, -51700, 98234, -68544, -61838, 29467, 46603, -18221, -35441, 74537, 40327, -58293, 75755, -57301, -7532, -94163, 18179, -14388, -22258, -46417, -48285, 18242, -77551, 82620, 250, -20060, -79568, -77259, 82052, -98897, -75464, 48773, -79040, -11293, 45941, -67876, -69204, -46477, -46107, 792, 60546, -34573, -12879, -94562, 20356, -48004, -62429, 96242, 40594, 2099, 99494, 25724, -39394, -2388, -18563, -56510, -83570, -29214, 3015, 74454, 74197, 76678, -46597, 60630, -76093, 37578, -82045, -24077, 62082, -87787, -74936, 58687, 12200, -98952, 70155, -77370, 21710, -84625, -60556, -84128, 925, 65474, -15741, -94619, 88377, 89334, 44749, 22002, -45750, -93081, -14600, -83447, 46691, 85040, -66447, -80085, 56308, 44310, 24979, -29694, 57991, 4675, -71273, -44508, 13615, -54710, 23552, -78253, -34637, 50497, 68706, 81543, -88408, -21405, 6001, -33834, -21570, -46692, -25344, 20310, 71258, -97680, 11721, 59977, 59247, -48949, 98955, -50276, -80844, -27935, -76102, 55858, -33492, 40680, 66691, -33188, 8284, 64893, -7528, 6019, -85523, 8434, -64366, -56663, 26862, 30008, -7611, -12179, -70076, 21426, -11261, -36864, -61937, -59677, 929, -21052, 3848, -20888, -16065, 98995, -32293, -86121, -54564, 77831, 68602, 74977, 31658, 40699, 29755, 98424, 80358, -69337, 26339, 13213, -46016, -18331, 64713, -46883, -58451, -70024, -92393, -4088, 70628, -51185, 71164, -75791, -1636, -29102, -16929, -87650, -84589, -24229, -42137, -15653, 94825, 13042, 88499, -47100, -90358, -7180, 29754, -65727, -42659, -85560, -9037, -52459, 20997, -47425, 17318, 21122, 20472, -23037, 65216, -63625, -7877, -91907, 24100, -72516, 22903, -85247, -8938, 73878, 54953, 87480, -31466, -99524, 35369, -78376, 89984, -15982, 94045, -7269, 23319, -80456, -37653, -76756, 2909, 81936, 54958, -12393, 60560, -84664, -82413, 66941, -26573, -97532, 64460, 18593, -85789, -38820, -92575, -43663, -89435, 83272, -50585, 13616, -71541, -53156, 727, -27644, 16538, 34049, 57745, 34348, 35009, 16634, -18791, 23271, -63844, 95817, 21781, 16590, 59669, 15966, -6864, 48050, -36143, 97427, -59390, 96931, 78939, -1958, 50777, 43338, -51149, 39235, -27054, -43492, 67457, -83616, 37179, 10390, 85818, 2391, 73635, 87579, -49127, -81264, -79023, -81590, 53554, -74972, -83940, -13726, -39095, 29174, 78072, 76104, 47778, 25797, -29515, -6493, -92793, 22481, -36197, -65560, 42342, 15750, 97556, 99634, -56048, -35688, 13501, 63969, -74291, 50911, 39225, 93702, -3490, -59461, -30105, -46761, -80113, 92906, -68487, 50742, 36152, -90240, -83631, 24597, -50566, -15477, 18470, 77038, 40223, -80364, -98676, 70957, -63647, 99537, 13041, 31679, 86631, 37633, -16866, 13686, -71565, 21652, -46053, -80578, -61382, 68487, -6417, 4656, 20811, 67013, -30868, -11219, 46, 74944, 14627, 56965, 42275, -52480, 52162, -84883, -52579, -90331, 92792, 42184, -73422, -58440, 65308, -25069, 5475, -57996, 59557, -17561, 2826, -56939, 14996, -94855, -53707, 99159, 43645, -67719, -1331, 21412, 41704, 31612, 32622, 1919, -69333, -69828, 22422, -78842, 57896, -17363, 27979, -76897, 35008, 46482, -75289, 65799, 20057, 7170, 41326, -76069, 90840, -81253, -50749, 3649, -42315, 45238, -33924, 62101, 96906, 58884, -7617, -28689, -66578, 62458, 50876, -57553, 6739, 41014, -64040, -34916, 37940, 13048, -97478, -11318, -89440, -31933, -40357, -59737, -76718, -14104, -31774, 28001, 4103, 41702, -25120, -31654, 63085, -3642, 84870, -83896, -76422, -61520, 12900, 88678, 85547, 33132, -88627, 52820, 63915, -27472, 78867, -51439, 33005, -23447, -3271, -39308, 39726, -74260, -31874, -36893, 93656, 910, -98362, 60450, -88048, 99308, 13947, 83996, -90415, -35117, 70858, -55332, -31721, 97528, 82982, -86218, 6822, 25227, 36946, 97077, -4257, -41526, 56795, 89870, 75860, -70802, 21779, 14184, -16511, -89156, -31422, 71470, 69600, -78498, 74079, -19410, 40311, 28501, 26397, -67574, -32518, 68510, 38615, 19355, -6088, -97159, -29255, -92523, 3023, -42536, -88681, 64255, 41206, 44119, 52208, 39522, -52108, 91276, -70514, 83436, 63289, -79741, 9623, 99559, 12642, 85950, 83735, -21156, -67208, 98088, -7341, -27763, -30048, -44099, -14866, -45504, -91704, 19369, 13700, 10481, -49344, -85686, 33994, 19672, 36028, 60842, 66564, -24919, 33950, -93616, -47430, -35391, -28279, 56806, 74690, 39284, -96683, -7642, -75232, 37657, -14531, -86870, -9274, -26173, 98640, 88652, 64257, 46457, 37814, -19370, 9337, -22556, -41525, 39105, -28719, 51611, -93252, 98044, -90996, 21710, -47605, -64259, -32727, 53611, -31918, -3555, 33316, -66472, 21274, -37731, -2919, 15016, 48779, -88868, 1897, 41728, 46344, -89667, 37848, 68092, -44011, 85354, -43776, 38739, -31423, -66330, 65167, -22016, 59405, 34328, -60042, 87660, -67698, -59174, -1408, -46809, -43485, -88807, -60489, 13974, 22319, 55836, -62995, -37375, -4185, 32687, -36551, -75237, 58280, 26942, -73756, 71756, 78775, -40573, 14367, -71622, -77338, 24112, 23414, -7679, -51721, 87492, 85066, -21612, 57045, 10673, -96836, 52461, -62218, -9310, 65862, -22748, 89906, -96987, -98698, 26956, -43428, 46141, 47456, 28095, 55952, 67323, -36455, -60202, -43302, -82932, 42020, 77036, 10142, 60406, 70331, 63836, 58850, -66752, 52109, 21395, -10238, -98647, -41962, 27778, 69060, 98535, -28680, -52263, -56679, 66103, -42426, 27203, 80021, 10153, 58678, 36398, 63112, 34911, 20515, 62082, -15659, -40785, 27054, 43767, -20289, 65838, -6954, -60228, -72226, 52236, -35464, 25209, -15462, -79617, -41668, -84083, 62404, -69062, 18913, 46545, 20757, 13805, 24717, -18461, -47009, -25779, 68834, 64824, 34473, 39576, 31570, 14861, -15114, -41233, 95509, 68232, 67846, 84902, -83060, 17642, -18422, 73688, 77671, -26930, 64484, -99637, 73875, 6428, 21034, -73471, 19664, -68031, 15922, -27028, 48137, 54955, -82793, -41144, -10218, -24921, -28299, -2288, 68518, -54452, 15686, -41814, 66165, -72207, -61986, 80020, 50544, -99500, 16244, 78998, 40989, 14525, -56061, -24692, -94790, 21111, 37296, -90794, 72100, 70550, -31757, 17708, -74290, 61910, 78039, -78629, -25033, 73172, -91953, 10052, 64502, 99585, -1741, 90324, -73723, 68942, 28149, 30218, 24422, 16659, 10710, -62594, 94249, 96588, 46192, 34251, 73500, -65995, -81168, 41412, -98724, -63710, -54696, -52407, 19746, 45869, 27821, -94866, -76705, -13417, -61995, -71560, 43450, 67384, -8838, -80293, -28937, 23330, -89694, -40586, 46918, 80429, -5475, 78013, 25309, -34162, 37236, -77577, 86744, 26281, -29033, -91813, 35347, 13033, -13631, -24459, 3325, -71078, -75359, 81311, 19700, 47678, -74680, -84113, 45192, 35502, 37675, 19553, 76522, -51098, -18211, 89717, 4508, -82946, 27749, 85995, 89912, -53678, -64727, -14778, 32075, -63412, -40524, 86440, -2707, -36821, 63850, -30883, 67294, -99468, -23708, 34932, 34386, 98899, 29239, -23385, 5897, 54882, 98660, 49098, 70275, 17718, 88533, 52161, 63340, 50061, -89457, 19491, -99156, 24873, -17008, 64610, -55543, 50495, 17056, -10400, -56678, -29073, -42960, -76418, 98562, -88104, -96255, 10159, -90724, 54011, 12052, 45871, -90933, -69420, 67039, 37202, 78051, -52197, -40278, -58425, 65414, -23394, -1415, 6912, -53447, 7352, 17307, -78147, 63727, 98905, 55412, -57658, -32884, -44878, 22755, 39730, 3638, 35111, 39777, 74193, 38736, -11829, -61188, -92757, 55946, -71232, -63032, -83947, 39147, -96684, -99233, 25131, -32197, 24406, -55428, -61941, 25874, -69453, 64483, -19644, -68441, 12783, 87338, -48676, 66451, -447, -61590, 50932, -11270, 29035, 65698, -63544, 10029, 80499, -9461, 86368, 91365, -81810, -71914, -52056, -13782, 44240, -30093, -2437, 24007, 67581, -17365, -69164, -8420, -69289, -29370, 48010, 90439, 13141, 69243, 50668, 39328, 61731, 78266, -81313, 17921, -38196, 55261, 9948, -24970, 75712, -72106, 28696, 7461, 31621, 61047, 51476, 56512, 11839, -96916, -82739, 28924, -99927, 58449, 37280, 69357, 11219, -32119, -62050, -48745, -83486, -52376, 42668, 82659, 68882, 38773, 46269, -96005, 97630, 25009, -2951, -67811, 99801, 81587, -79793, -18547, -83086, 69512, 33127, -92145, -88497, 47703, 59527, 1909, 88785, -88882, 69188, -46131, -5589, -15086, 36255, -53238, -33009, 82664, 53901, 35939, -42946, -25571, 33298, 69291, 53199, 74746, -40127, -39050, 91033, 51717, -98048, 87240, 36172, 65453, -94425, -63694, -30027, 59004, 88660, 3649, -20267, -52565, -67321, 34037, 4320, 91515, -56753, 60115, 27134, 68617, -61395, -26503, -98929, -8849, -63318, 10709, -16151, 61905, -95785, 5262, 23670, -25277, 90206, -19391, 45735, 37208, -31992, -92450, 18516, -90452, -58870, -58602, 93383, 14333, 17994, 82411, -54126, -32576, 35440, -60526, -78764, -25069, -9022, -394, 92186, -38057, 55328, -61569, 67780, 77169, 19546, -92664, -94948, 44484, -13439, 83529, 27518, -48333, 72998, 38342, -90553, -98578, -76906, 81515, -16464, 78439, 92529, 35225, -39968, -10130, -7845, -32245, -74955, -74996, 67731, -13897, -82493, 33407, 93619, 59560, -24404, -57553, 19486, -45341, 34098, -24978, -33612, 79058, 71847, 76713, -95422, 6421, -96075, -59130, -28976, -16922, -62203, 69970, 68331, 21874, 40551, 89650, 51908, 58181, 66480, -68177, 34323, -3046, -49656, -59758, 43564, -10960, -30796, 15473, -20216, 46085, -85355, 41515, -30669, -87498, 57711, 56067, 63199, -83805, 62042, 91213, -14606, 4394, -562, 74913, 10406, 96810, -61595, 32564, 31640, -9732, 42058, 98052, -7908, -72330, 1558, -80301, 34878, 32900, 3939, -8824, 88316, 20937, 21566, -3218, -66080, -31620, 86859, 54289, 90476, -42889, -15016, -18838, 75456, 30159, -67101, 42328, -92703, 85850, -5475, 23470, -80806, 68206, 17764, 88235, 46421, -41578, 74005, -81142, 80545, 20868, -1560, 64017, 83784, 68863, -97516, -13016, -72223, 79630, -55692, 82255, 88467, 28007, -34686, -69049, -41677, 88535, -8217, 68060, -51280, 28971, 49088, 49235, 26905, -81117, -44888, 40623, 74337, -24662, 97476, 79542, -72082, -35093, 98175, -61761, -68169, 59697, -62542, -72965, 59883, -64026, -37656, -92392, -12113, -73495, 98258, 68379, -21545, 64607, -70957, -92254, -97460, -63436, -8853, -19357, -51965, -76582, 12687, -49712, 45413, -60043, 33496, 31539, -57347, 41837, 67280, -68813, 52088, -13155, -86430, -15239, -45030, 96041, 18749, -23992, 46048, 35243, -79450, 85425, -58524, 88781, -39454, 53073, -48864, -82289, 39086, 82540, -11555, 25014, -5431, -39585, -89526, 2705, 31953, -81611, 36985, -56022, 68684, -27101, 11422, 64655, -26965, -63081, -13840, -91003, -78147, -8966, 41488, 1988, 99021, -61575, -47060, 65260, -23844, -21781, -91865, -19607, 44808, 2890, 63692, -88663, -58272, 15970, -65195, -45416, -48444, -78226, -65332, -24568, 42833, -1806, -71595, 80002, -52250, 30952, 48452, -90106, 31015, -22073, 62339, 63318, 78391, 28699, 77900, -4026, -76870, -45943, 33665, 9174, -84360, -22684, -16832, -67949, -38077, -38987, -32847, 51443, -53580, -13505, 9344, -92337, 26585, 70458, -52764, -67471, -68411, -1119, -2072, -93476, 67981, 40887, -89304, -12235, 41488, 1454, 5355, -34855, -72080, 24514, -58305, 3340, 34331, 8731, 77451, -64983, -57876, 82874, 62481, -32754, -39902, 22451, -79095, -23904, 78409, -7418, 77916};
    System.out.println(threeSum(nums));
  }
}

16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 16. 3Sum Closest
 *
 * https://leetcode.com/problems/3sum-closest/description/[3Sum Closest - LeetCode]
 *
 * Given an array nums of n integers and an integer target, find three integers
 * in nums such that the sum is closest to target. Return the sum of the three
 * integers. You may assume that each input would have exactly one solution.
 *
 * .Example:
 * [source]
 * ----
 * Given array nums = [-1, 2, 1, -4], and target = 1.
 *
 * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-15 00:55
 */
public class _0016_3SumClosest {
    /**
     * Runtime: 4 ms, faster than 96.20% of Java online submissions for 3Sum Closest.
     *
     * Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for 3Sum Closest.
     */
    public int threeSumClosest(int[] nums, int target) {
        if (Objects.isNull(nums)) {
            return target;
        }
        Arrays.sort(nums);
        int length = nums.length;
        int result = 0;
        int difference = Integer.MAX_VALUE;
        for (int head = 0; head < length; head++) {
            int midd = head + 1;
            int tail = length - 1;
            while (midd < tail) {
                int sum = nums[head] + nums[midd] + nums[tail];
                if (sum > target) {
                    while (midd < tail && nums[tail - 1] == nums[tail]) {
                        tail--;
                    }
                    tail--;
                } else if (sum < target) {
                    while (midd < tail && nums[midd] == nums[midd + 1]) {
                        midd++;
                    }
                    midd++;
                } else {
                    return target;
                }
                int tempDiff = Math.abs(sum - target);
                if (tempDiff < difference) {
                    result = sum;
                    difference = tempDiff;
                }
            }
        }

        return result;
    }


    /**
     * Runtime: 73 ms, faster than 7.18% of Java online submissions for 3Sum Closest.
     *
     * Memory Usage: 36.7 MB, less than 100.00% of Java online submissions for 3Sum Closest.
     */
    public int threeSumClosestO3(int[] nums, int target) {
        if (Objects.isNull(nums)) {
            return target;
        }
        int length = nums.length;
        if (length <= 3) {
            int result = 0;
            for (int i = 0; i < length; i++) {
                result += nums[i];
            }
            return result;
        }

        int result = 0;
        int difference = Integer.MAX_VALUE;

        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                for (int k = j + 1; k < length; k++) {
                    int sum = nums[i] + nums[j] + nums[k];
                    int temp = Math.abs(target - sum);
                    if (temp < difference) {
                        difference = temp;
                        result = sum;
                    }
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0016_3SumClosest solution = new _0016_3SumClosest();
        int r1 = solution.threeSumClosest(new int[]{-1, 2, 1, -4}, 1);
        System.out.println((2 == r1) + " : " + r1);
    }
}

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

200px Telephone keypad2.svg

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

解题分析

这道题可以使用回溯来解决:每次取出一个数字对应的字母列表,遍历追加到上一次的字母组合中。依次进行,直到数字取完为止。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 17. Letter Combinations of a Phone Number
 *
 * https://leetcode.com/problems/letter-combinations-of-a-phone-number/[Letter Combinations of a Phone Number - LeetCode]
 *
 * Given a string containing digits from 2-9 inclusive, return all possible letter
 * combinations that the number could represent.
 *
 * A mapping of digit to letters (just like on the telephone buttons) is given below.
 * Note that 1 does not map to any letters.
 *
 * * 1 - {},
 * * 2 - {'a','b','c'},
 * * 3 - {'d','e','f'},
 * * 4 - {'g','h','i'},
 * * 5 - {'j','k','l'},
 * * 6 - {'m','n','o'},
 * * 7 - {'p','q','r','s'},
 * * 8 - {'t','u','v'},
 * * 9 - {'w','x','y','z'},
 * * 0 - {}
 *
 * .Example:
 * [source]
 * ----
 * Input: "23"
 * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 * ----
 *
 * *Note:*
 *
 * Although the above answer is in lexicographical order, your answer could be in any order you want.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-19 00:19
 */
public class _0017_LetterCombinationsOfAPhoneNumber {

  private List<String> result = new ArrayList<>();
  public List<String> letterCombinations(String digits) {
    if (Objects.isNull(digits) || digits.length() == 0) {
      return result;
    }
    backtrack(digits, "");
    return result;
  }
  private void backtrack(String digits, String letters) {
    if (digits.length() == 0) {
      result.add(letters);
      return;
    }
    String let = getLetterByChar(digits.charAt(0));
    String sub = digits.substring(1);
    if (let.length() > 0) {
      for (int i = 0; i < let.length(); i++) {
        backtrack(sub, letters + let.charAt(i));
      }
    } else {
      backtrack(sub, letters);
    }
  }

  private String getLetterByChar(char c) {
    switch (c) {
      case '2':
        return "abc";
      case '3':
        return "def";
      case '4':
        return "ghi";
      case '5':
        return "jkl";
      case '6':
        return "mno";
      case '7':
        return "pqrs";
      case '8':
        return "tuv";
      case '9':
        return "wxyz";
      default:
        return "";
    }
  }

  /**
   * Runtime: 32 ms, faster than 6.94% of Java online submissions for Letter Combinations of a Phone Number.
   *
   * Memory Usage: 36.2 MB, less than 99.10% of Java online submissions for Letter Combinations of a Phone Number.
   */
  public List<String> letterCombinations1(String digits) {
    if (Objects.isNull(digits) || digits.length() == 0) {
      return Collections.EMPTY_LIST;
    }

    char[] chars = digits.toCharArray();
    List<Integer> integers = new ArrayList<>();
    int length = chars.length;
    for (int i = 0; i < length; i++) {
      int num = chars[i] - '0';
      if (num > 1) {
        integers.add(num);
      }
    }
    char[][] int2chars = new char[][]{
      {},
      {},
      {'a', 'b', 'c'},
      {'d', 'e', 'f'},
      {'g', 'h', 'i'},
      {'j', 'k', 'l'},
      {'m', 'n', 'o'},
      {'p', 'q', 'r', 's'},
      {'t', 'u', 'v'},
      {'w', 'x', 'y', 'z'},
    };
    int size = integers.size();
    char[][] selectedChars = new char[size][];
    for (int i = 0; i < size; i++) {
      selectedChars[i] = int2chars[integers.get(i)];
    }

    return combine(selectedChars, 0);
  }

  public List<String> combine(char[][] chars, int depth) {
    List<String> result = new ArrayList<>();
    char[] rowChars = chars[depth];
    if (depth == chars.length - 1) {
      for (int i = 0; i < rowChars.length; i++) {
        result.add(rowChars[i] + "");
      }
    } else {
      List<String> strings = combine(chars, depth + 1);
      for (int i = 0; i < rowChars.length; i++) {
        char aChar = rowChars[i];
        strings.forEach(s -> result.add(aChar + s));
      }
    }
    return result;
  }


  public static void main(String[] args) {
    _0017_LetterCombinationsOfAPhoneNumber solution = new _0017_LetterCombinationsOfAPhoneNumber();
    List<String> r1 = solution.letterCombinations("23");
    Collections.sort(r1);
    System.out.println(Arrays.toString(r1.toArray(new String[0])));
    List<String> s1 = Arrays.asList("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf");
    Collections.sort(s1);
    System.out.println(s1.equals(r1) + " : " + Arrays.toString(r1.toArray(new String[0])));
  }

}

18. 4Sum

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 18. 4Sum
 *
 * https://leetcode.com/problems/4sum/description/[4Sum - LeetCode]
 *
 * Given an array `nums` of n integers and an integer `target`, are there
 * elements `a`, `b`, `c`, and `d` in `nums` such that `a + b + c + d = target`?
 * Find all unique quadruplets in the array which gives the sum of target.
 *
 * == Note
 *
 * The solution set must not contain duplicate quadruplets.
 *
 * .Example:
 * [source]
 * ----
 * Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
 *
 * A solution set is:
 * [
 *   [-1,  0, 0, 1],
 *   [-2, -1, 1, 2],
 *   [-2,  0, 0, 2]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-15 00:58
 */
public class _0018_4Sum {
    /**
     * Runtime: 4 ms, faster than 94.46% of Java online submissions for 4Sum.
     *
     * Memory Usage: 40.7 MB, less than 52.17% of Java online submissions for 4Sum.
     */
    public List<List<Integer>> fourSum(int[] nums, int target) {
        int numCount = 4;
        if (Objects.isNull(nums) || nums.length < numCount) {
            return Collections.emptyList();
        }

        Arrays.sort(nums);
        int length = nums.length;
        if (target < numCount * nums[0] || numCount * nums[length - 1] < target) {
            return Collections.emptyList();
        }

        List<List<Integer>> result = new LinkedList<>();
        for (int i = 0; i < length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int twoSumTarget = target - nums[i] - nums[j];
                int minTwoSum = nums[j + 1] + nums[j + 2];
                int maxTwoSum = nums[length - 1] + nums[length - 2];
                if (twoSumTarget < minTwoSum || maxTwoSum < twoSumTarget) {
                    continue;
                }
                for (int m = j + 1, n = length - 1; m < n; ) {
                    int twoSum = nums[m] + nums[n];
                    if (twoSum < twoSumTarget) {
                        while (m < n && nums[m] == nums[m + 1]) {
                            m++;
                        }
                        m++;
                    } else if (twoSumTarget < twoSum) {
                        while (m < n && nums[n - 1] == nums[n]) {
                            n--;
                        }
                        n--;
                    } else {
                        result.add(Arrays.asList(nums[i], nums[j], nums[m], nums[n]));

                        while (m < n && nums[m] == nums[m + 1]) {
                            m++;
                        }
                        m++;

                        while (m < n && nums[n - 1] == nums[n]) {
                            n--;
                        }
                        n--;
                    }
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        _0018_4Sum solution = new _0018_4Sum();
        List<List<Integer>> r1 = solution.fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0);
        System.out.println(Arrays.deepToString(r1.toArray()));
    }
}

19. Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

解题分析

快慢指针

0019 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 19. Remove Nth Node From End of List
 *
 * https://leetcode.com/problems/remove-nth-node-from-end-of-list/[Remove Nth Node From End of List - LeetCode]
 *
 * Given a linked list, remove the n-th node from the end of list and return its head.
 *
 * .Example 1:
 * [source]
 * ----
 * Given linked list: 1->2->3->4->5, and n = 2.
 *
 * After removing the second node from the end, the linked list becomes 1->2->3->5.
 * ----
 *
 * *Note:*
 *
 * Given n will always be valid.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-26 20:17
 */
public class _0019_RemoveNthNodeFromEndOfList {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
     *
     * Memory Usage: 34.6 MB, less than 100.00% of Java online submissions for Remove Nth Node From End of List.
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (Objects.isNull(head) || n == 0) {
            return head;
        }
        ListNode p1 = head;
        int length = 1;
        while (Objects.nonNull(p1.next) && length <= n) {
            p1 = p1.next;
            length++;
        }
        if (Objects.isNull(p1.next) && length == n) {
            return head.next;
        }
        if (Objects.isNull(p1.next) && length < n) {
            return head;
        }

        ListNode p2 = head;
        while (Objects.nonNull(p1.next)) {
            p1 = p1.next;
            p2 = p2.next;
        }
        if (Objects.nonNull(p2.next)) {
            p2.next = p2.next.next;
        }
        return head;
    }

    public static void main(String[] args) {
        _0019_RemoveNthNodeFromEndOfList solution = new _0019_RemoveNthNodeFromEndOfList();

        ListNode r5 = solution.removeNthFromEnd(build(Arrays.asList(1, 2)), 1);
        printListNode(r5);

        ListNode r4 = solution.removeNthFromEnd(build(Arrays.asList(1)), 1);
        printListNode(r4);

        ListNode r1 = solution.removeNthFromEnd(build(Arrays.asList(1, 2, 3, 4, 5)), 2);
        printListNode(r1);

        ListNode r2 = solution.removeNthFromEnd(build(Arrays.asList(1, 2, 3, 4, 5)), 6);
        printListNode(r2);

        ListNode r3 = solution.removeNthFromEnd(build(Arrays.asList()), 2);
        printListNode(r3);
    }
}

20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Stack;

/**
 * = 20. Valid Parentheses
 *
 * https://leetcode.com/problems/valid-parentheses/[Valid Parentheses - LeetCode]
 *
 * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 *
 * An input string is valid if:
 *
 * Open brackets must be closed by the same type of brackets.
 * Open brackets must be closed in the correct order.
 * Note that an empty string is also considered valid.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "()"
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "()[]{}"
 * Output: true
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: "(]"
 * Output: false
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: "([)]"
 * Output: false
 * ----
 *
 * .Example 5:
 * [source]
 * ----
 * Input: "{[]}"
 * Output: true
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-26 08:12
 */
public class _0020_ValidParentheses {
    /**
     * Runtime: 2 ms, faster than 60.99% of Java online submissions for Valid Parentheses.
     *
     * Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Valid Parentheses.
     */
    public boolean isValid(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return true;
        }
        Map<Character, Character> parenthesesMap = new HashMap<>(3);
        parenthesesMap.put('(', ')');
        parenthesesMap.put('{', '}');
        parenthesesMap.put('[', ']');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char aChar = s.charAt(i);
            if (parenthesesMap.containsKey(aChar)) {
                stack.push(aChar);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char peek = stack.pop();
                if (aChar != parenthesesMap.get(peek)) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        _0020_ValidParentheses solution = new _0020_ValidParentheses();

        String s7 = "[";
        boolean valid7 = solution.isValid(s7);
        System.out.println((false == valid7) + " : " + s7);

        String s6 = "]";
        boolean valid6 = solution.isValid(s6);
        System.out.println((false == valid6) + " : " + s6);

        String s1 = "()";
        boolean valid1 = solution.isValid(s1);
        System.out.println((true == valid1) + " : " + s1);

        String s2 = "()[]{}";
        boolean valid2 = solution.isValid(s2);
        System.out.println((true == valid2) + " : " + s2);

        String s3 = "(]";
        boolean valid3 = solution.isValid(s3);
        System.out.println((false == valid3) + " : " + s3);

        String s4 = "([)]";
        boolean valid4 = solution.isValid(s4);
        System.out.println((false == valid4) + " : " + s4);

        String s5 = "{[]}";
        boolean valid5 = solution.isValid(s5);
        System.out.println((true == valid5) + " : " + s5);
    }
}

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.isOrder;

/**
 * = 21. Merge Two Sorted Lists
 *
 * https://leetcode.com/problems/merge-two-sorted-lists/[Merge Two Sorted Lists - LeetCode]
 *
 * Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
 *
 * .Example:
 * [source]
 * ----
 * Input: 1->2->4, 1->3->4
 * Output: 1->1->2->3->4->4
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-26 08:49
 */
public class _0021_MergeTwoSortedLists {
  public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (Objects.isNull(l1) && Objects.isNull(l2)) {
      return null;
    }
    ListNode dummy = new ListNode();
    ListNode tail = dummy;
    while (Objects.nonNull(l1) && Objects.nonNull(l2)) {
      if (l1.val < l2.val) {
        tail.next = l1;
        l1 = l1.next;
      } else {
        tail.next = l2;
        l2 = l2.next;
      }
      tail = tail.next;
    }
    if (Objects.isNull(l1)) {
      tail.next = l2;
    }
    if (Objects.isNull(l2)) {
      tail.next = l1;
    }
    return dummy.next;
  }

  /**
   * Runtime: 1 ms, faster than 28.15% of Java online submissions for Merge Two Sorted Lists.
   *
   * Memory Usage: 39.8 MB, less than 14.45% of Java online submissions for Merge Two Sorted Lists.
   */
  public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
    if (Objects.isNull(l1)) {
      return l2;
    }
    if (Objects.isNull(l2)) {
      return l1;
    }
    ListNode result = null;
    ListNode p1 = l1;
    ListNode p2 = l2;
    ListNode tail = null;

    while (Objects.nonNull(p1) && Objects.nonNull(p2)) {
      int v1 = p1.val;
      int v2 = p2.val;
      ListNode temp = null;
      if (v1 < v2) {
        temp = p1;
        p1 = p1.next;
      } else {
        temp = p2;
        p2 = p2.next;
      }
      if (Objects.isNull(tail)) {
        result = temp;
        tail = temp;
      } else {
        tail.next = temp;
        tail = temp;
      }
    }
    if (Objects.isNull(p1)) {
      tail.next = p2;
    }

    if (Objects.isNull(p2)) {
      tail.next = p1;
    }

    return result;
  }

  public static void main(String[] args) {
    _0021_MergeTwoSortedLists solution = new _0021_MergeTwoSortedLists();
    ListNode l1 = build(Arrays.asList());
    ListNode l2 = build(Arrays.asList());
    ListNode r1 = solution.mergeTwoLists(l1, l2);
    System.out.println(isOrder(r1));
  }
}

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "",
  ")(",
  "))()",   "()((",
  "()()()"
]

解题分析

0022 mindmap

使用回溯法解题时,需要关注的一个点是,在递归调用时,为了保证结果是有效的括号对,则添加的闭区间符号不能多于开区间符号。也就是,保证添加在添加一个闭区间符号之前,要先添加了对应的开区间符号。所以,就要注意闭区间的判断,是跟开区间大小判断,而不是括号数量。并不是所有的排列组合都符合我们的需求。

0022 0
0022 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.diguage.algorithm.leetcode;


import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/**
 * = 22. Generate Parentheses
 *
 * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
 *
 * For example, given n = 3, a solution set is:
 *
 * ----
 * [
 *   "((()))",
 *   "(()())",
 *   "(())()",
 *   "()(())",
 *   "()()()"
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-27 08:11
 */
public class _0022_GenerateParentheses {
  /**
   * Runtime: 2 ms, faster than 21.88% of Java online submissions for Generate Parentheses.
   *
   * Memory Usage: 45.3 MB, less than 5.16% of Java online submissions for Generate Parentheses.
   *
   * Copy from: https://leetcode.com/problems/generate-parentheses/solution/[Generate Parentheses solution - LeetCode]
   */
  public List<String> generateParenthesis(int n) {
    List<String> ans = new LinkedList<>();
    backtrack(ans, "", 0, 0, n);
    return ans;
  }

  public void backtrack(List<String> result, String curr, int open, int close, int n) {
    if (curr.length() == 2 * n) {
      result.add(curr);
      return;
    }
    if (open < n) {
      backtrack(result, curr + "(", open + 1, close, n);
    }
    if (close < open) {
      backtrack(result, curr + ")", open, close + 1, n);
    }
  }


  public static void main(String[] args) {
    _0022_GenerateParentheses solution = new _0022_GenerateParentheses();

    List<String> r3 = solution.generateParenthesis(3);
    r3.sort(Comparator.naturalOrder());
    List<String> p3 = Arrays.asList("((()))", "(()())", "(())()", "()(())", "()()()");
    p3.sort(Comparator.naturalOrder());
    System.out.println("▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽");
    System.out.println((p3.equals(r3)) + " : \n"
      + Arrays.toString(r3.toArray(new String[0])) + "\n"
      + Arrays.toString(p3.toArray(new String[0])));
    System.out.println("△△△△△△△△△△△△△△△△△△△△");

    List<String> r4 = solution.generateParenthesis(4);
    r4.sort(Comparator.naturalOrder());
    List<String> p4 = Arrays.asList("(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()");
    p4.sort(Comparator.naturalOrder());
    System.out.println("▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽▽");
    System.out.println((p4.equals(r4)) + " : \n"
      + Arrays.toString(r4.toArray(new String[0])) + "\n"
      + Arrays.toString(p4.toArray(new String[0])));
    System.out.println("△△△△△△△△△△△△△△△△△△△△");
  }
}

思考题

有机会思考尝试一下广度优先遍历。

23. Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.diguage.algorithm.leetcode;

import java.util.*;

import com.diguage.algorithm.util.ListNode;

import static com.diguage.algorithm.util.ListNodeUtils.*;

/**
 * = 23. Merge k Sorted Lists
 *
 * https://leetcode.com/problems/merge-k-sorted-lists/[(8) Merge k Sorted Lists - LeetCode]
 *
 * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
 *
 * .Example:
 * [source]
 * ----
 * Input:
 * [
 *   1->4->5,
 *   1->3->4,
 *   2->6
 * ]
 * Output: 1->1->2->3->4->4->5->6
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-22 12:40:12
 */
public class _0023_MergeKSortedLists {

  public ListNode mergeKLists(ListNode[] lists) {
    PriorityQueue<ListNode> heap = new PriorityQueue<>((l1, l2) -> l1.val - l2.val);
    for (ListNode l : lists) {
      if (Objects.nonNull(l)) {
        heap.add(l);
      }
    }
    ListNode dummy = new ListNode();
    ListNode curr = dummy;
    while (!heap.isEmpty()) {
      ListNode node = heap.poll();
      curr.next = node;
      curr = curr.next;
      if (Objects.nonNull(node.next)) {
        heap.add(node.next);
      }
    }
    return dummy.next;
  }

  /**
   * Runtime: 40 ms, faster than 20.21% of Java online submissions for Merge k Sorted Lists.
   *
   * Memory Usage: 39.6 MB, less than 74.87% of Java online submissions for Merge k Sorted Lists.
   */
  public ListNode mergeKLists1(ListNode[] lists) {
    PriorityQueue<ListNode> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o.val));
    for (ListNode list : lists) {
      if (Objects.nonNull(list)) {
        queue.add(list);
      }
    }

    ListNode result = null;
    ListNode tail = null;
    for (ListNode node = queue.poll(); Objects.nonNull(node); ) {
      if (Objects.isNull(result)) {
        result = node;
      }
      ListNode next = node.next;
      if (Objects.nonNull(next)) {
        queue.add(next);
      }
      if (Objects.nonNull(tail)) {
        tail.next = node;
      }
      tail = node;
      node = queue.poll();
    }

    return result;
  }

  public static void main(String[] args) {
    ListNode node1 = build(Arrays.asList(1, 4, 5));
    ListNode node2 = build(Arrays.asList(1, 3, 4));
    ListNode node3 = build(Arrays.asList(2, 6));
    ListNode[] lists = new ListNode[]{node1, node2, node3};
    _0023_MergeKSortedLists solution = new _0023_MergeKSortedLists();
    ListNode r1 = solution.mergeKLists(lists);
    System.out.println(isOrder(r1));
  }
}

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

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

Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.

思考题

尝试使用递归来实现一下。

参考资料

Given a linked list, swap every two adjacent nodes and return its head.

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

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 24. Swap Nodes in Pairs
 *
 * https://leetcode.com/problems/swap-nodes-in-pairs/[Swap Nodes in Pairs - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-03 20:12
 */
public class _0024_SwapNodesInPairs {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Swap Nodes in Pairs.
     * Memory Usage: 37.3 MB, less than 5.50% of Java online submissions for Swap Nodes in Pairs.
     */
    public ListNode swapPairs(ListNode head) {
        if (Objects.isNull(head) || Objects.isNull(head.next)) {
            return head;
        }
        ListNode result = head.next;
        ListNode prevNode = new ListNode(0);
        prevNode.next = head;
        while (Objects.nonNull(head) && Objects.nonNull(head.next)) {
            ListNode second = head.next;
            head.next = second.next;
            second.next = head;
            prevNode.next = second;
            prevNode = head;
            head = head.next;
        }

        return result;
    }

    public static void main(String[] args) {
        _0024_SwapNodesInPairs solution = new _0024_SwapNodesInPairs();
        ListNode r1 = solution.swapPairs(build(asList(1, 2, 3, 4)));
        printListNode(r1);
    }
}

25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

Given this linked list: 1→2→3→4→5

For k = 2, you should return: 2→1→4→3→5

For k = 3, you should return: 3→2→1→4→5

Note:

  • Only constant extra memory is allowed.

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

1
Unresolved directive in 0025-reverse-nodes-in-k-group.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0025_ReverseNodesInKGroup.java[]

26. Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of `nums` being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of `nums` being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解题分析

把后面的数据向前拷贝。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 26. Remove Duplicates from Sorted Array
 *
 * https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/[Remove Duplicates from Sorted Array - LeetCode]
 *
 * Given a sorted array `nums`, remove the duplicates
 * *https://en.wikipedia.org/wiki/In-place_algorithm[in-place]* such that each
 * element appear only once and return the new length.
 *
 * Do not allocate extra space for another array, you must do this by *modifying
 * the input array* *https://en.wikipedia.org/wiki/In-place_algorithm[in-place]*
 * with O(1) extra memory.
 *
 * .Example 1:
 * [source]
 * ----
 * Given nums = [1,1,2],
 *
 * Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
 *
 * It doesn't matter what you leave beyond the returned length.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Given nums = [0,0,1,1,1,2,2,3,3,4],
 *
 * Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
 *
 * It doesn't matter what values are set beyond the returned length.
 * ----
 *
 * == Clarification
 *
 * Confused why the returned value is an integer but your answer is an array?
 *
 * Note that the input array is passed in by *reference*, which means modification to the input array will be known to the caller as well.
 *
 * Internally you can think of this:
 *
 * [source]
 * ----
 * // nums is passed in by reference. (i.e., without making a copy)
 * int len = removeDuplicates(nums);
 *
 * // any modification to nums in your function would be known by the caller.
 * // using the length returned by your function, it prints the first len elements.
 * for (int i = 0; i < len; i++) {
 * print(nums[i]);
 * }
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-19 18:34
 */
public class _0026_RemoveDuplicatesFromSortedArray {
  public static int removeDuplicates(int[] nums) {
    if (Objects.isNull(nums) || nums.length == 0) {
      return 0;
    }
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
      if (nums[i] != nums[j]) {
        i++;
        nums[i] = nums[j];
      }
    }
    return i + 1;
  }

  public static int removeDuplicates1(int[] nums) {
    if (nums == null || nums.length == 0) {
      return 0;
    }
    int result = nums.length;
    if (nums.length == 1) {
      return result;
    }

    int previousNum = nums[0];
    int minuendIndex = 0;
    for (int i = 1; i < nums.length; i++) {
      if (previousNum == nums[i]) {
        minuendIndex++;
        result--;
      } else {
        previousNum = nums[i];
      }
      if (minuendIndex > 0) {
        nums[i - minuendIndex] = nums[i];
      }
    }

    return result;
  }

  public static void main(String[] args) {
    int[] nums = {1, 2, 2};
    System.out.println(removeDuplicates(nums));
    System.out.println(Arrays.toString(nums));
  }
}

27. Remove Element

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of `nums` containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 27. Remove Element
 *
 * https://leetcode.com/problems/remove-element/description/[Remove Element - LeetCode]
 *
 * Given an array `nums` and a value `val`, remove all instances of that value
 * *https://en.wikipedia.org/wiki/In-place_algorithm[in-place]* and return the new length.
 *
 * Do not allocate extra space for another array, you must do this by *modifying
 * the input array* *https://en.wikipedia.org/wiki/In-place_algorithm[in-place]* with O(1) extra memory.
 *
 * The order of elements can be changed. It doesn't matter what you leave beyond the new length.
 *
 * .Example 1:
 * [source]
 * ----
 * Given nums = [3,2,2,3], val = 3,
 *
 * Your function should return length = 2, with the first two elements of nums being 2.
 *
 * It doesn't matter what you leave beyond the returned length.
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Given nums = [0,1,2,2,3,0,4,2], val = 2,
 *
 * Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
 *
 * Note that the order of those five elements can be arbitrary.
 *
 * It doesn't matter what values are set beyond the returned length.
 * ----
 *
 * == Clarification:
 *
 * Confused why the returned value is an integer but your answer is an array?
 *
 * Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
 *
 * Internally you can think of this:
 *
 * [source]
 * ----
 * // nums is passed in by reference. (i.e., without making a copy)
 * int len = removeElement(nums, val);
 *
 * // any modification to nums in your function would be known by the caller.
 * // using the length returned by your function, it prints the first len elements.
 * for (int i = 0; i < len; i++) {
 *     print(nums[i]);
 * }
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-19 18:55
 */
public class _0027_RemoveElement {
    public static int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int result = nums.length;
        int minuendIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            if (minuendIndex > 0) {
                nums[i - minuendIndex] = nums[i];
            }
            if (nums[i] == val) {
                result--;
                minuendIndex++;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0, 1, 2, 2, 3, 0, 4, 2};
        int val = 2;
        System.out.println(removeElement(nums, val));
        System.out.println(Arrays.toString(nums));
    }
}

28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

解题分析

直接截取字符串然后判断相等,算不算作弊?😆

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 28. Implement strStr()
 *
 * Implement `strStr()`.
 *
 * Return the index of the first occurrence of needle in haystack, or *-1* if needle is not part of haystack.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: haystack = "hello", needle = "ll"
 * Output: 2
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: haystack = "aaaaa", needle = "bba"
 * Output: -1
 * ----
 *
 * *Clarification:*
 *
 * What should we return when `needle` is an empty string? This is a great question to ask during an interview.
 *
 * For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's `strstr()`
 * and Java's `indexOf()`.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018
 */
public class _0028_ImplementStrStr {
  public int strStr(String haystack, String needle) {
    if (Objects.isNull(needle) || needle.length() == 0) {
      return 0;
    }
    for (int i = 0; i <= haystack.length() - needle.length(); i++) {
      if (haystack.charAt(i) == needle.charAt(0)) {
        String sub = haystack.substring(i, i + needle.length());
        if (needle.equals(sub)) {
          return i;
        }
      }
    }
    return -1;
  }

  // TODO 有必要学一下 KMP 算法了啊!
  public int strStr1(String source, String target) {
    if (source == null || target == null || target.length() > source.length()) {
      return -1;
    }
    if (target.length() == 0) {
      return 0;
    }
    char[] sA = source.toCharArray();
    char[] tA = target.toCharArray();
    for (int i = 0; i < source.length(); i++) {
      if (contain(sA, i, tA)) {
        return i;
      }
    }
    return -1;
  }

  private boolean contain(char[] source, int index, char[] target) {
    if (source.length - index < target.length) {
      return false;
    }
    for (int i = index, j = 0; j < target.length; i++, j++) {
      if (source[i] != target[j]) {
        return false;
      }
    }
    return true;
  }

  public static void main(String[] args) {
    _0028_ImplementStrStr result = new _0028_ImplementStrStr();
    System.out.println(result.strStr("a", "a"));
    System.out.println(result.strStr("hello", "ll"));
    System.out.println(result.strStr("aaaaa", "bba"));
  }
}

29. Divide Two Integers

Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

Return the quotient after dividing dividend by divisor.

The integer division should truncate toward zero.

Example 1:

Input: dividend = 10, divisor = 3
Output: 3

Example 2:

Input: dividend = 7, divisor = -3
Output: -2

Note:

  • Both dividend and divisor will be 32-bit signed integers.

  • The divisor will never be 0.

  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-231, 231 - 1]. For the purpose of this problem, assume that your function returns 231 - 1 when the division result overflows.

解题分析

思路其实挺简单,就是通过移位操作,把被除数不断翻倍到仅次于被除数的倍数,然后从被除数中减去这个值,剩下的部分再反复执行这个操作,直到被除数小于除数为止。

模仿这个思路 C++ bit manipulations - LeetCode Discuss 来实现的。

15 line easy understand solution. 129ms - LeetCode Discuss 这个思路也很棒。它并没有等把倍数计算到最大去减少,而是在翻倍过程中,每次都去减少;等翻倍太大,再以此"减半"。感觉效率更高!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.diguage.algorithm.leetcode;

/**
 * = 29. Divide Two Integers
 *
 * https://leetcode.com/problems/divide-two-integers/[Divide Two Integers - LeetCode]
 *
 * Given two integers `dividend` and `divisor`, divide two integers without using multiplication, division and mod operator.
 *
 * Return the quotient after dividing `dividend` by `divisor`.
 *
 * The integer division should truncate toward zero.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: dividend = 10, divisor = 3
 * Output: 3
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: dividend = 7, divisor = -3
 * Output: -2
 * ----
 *
 * *Note:*
 *
 * * Both dividend and divisor will be 32-bit signed integers.
 * * The divisor will never be 0.
 * * Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31^,  2^31^ − 1]. For the purpose of this problem, assume that your function returns 2^31^ − 1 when the division result overflows.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-14 16:46
 */
public class _0029_DivideTwoIntegers {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Divide Two Integers.
     *
     * Memory Usage: 34.3 MB, less than 6.06% of Java online submissions for Divide Two Integers.
     *
     * Copy from: https://leetcode.com/problems/divide-two-integers/discuss/13407/C%2B%2B-bit-manipulations[C++ bit manipulations - LeetCode Discuss]
     */
    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;
        }

        int sign = dividend > 0 ^ divisor > 0 ? -1 : 1;
        long ldividend = Math.abs((long) dividend);
        long ldivisor = Math.abs((long) divisor);
        int result = 0;
        while (ldividend >= ldivisor) {
            long temp = ldivisor;
            int mul = 1;
            while (temp << 1 <= ldividend) {
                temp <<= 1;
                mul <<= 1;
            }
            ldividend -= temp;
            result += mul;
        }
        return result * sign;
    }

    public static void main(String[] args) {
        _0029_DivideTwoIntegers solution = new _0029_DivideTwoIntegers();
        int r1 = solution.divide(10, 3);
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.divide(7, -3);
        System.out.println((r2 == -2) + " : " + r2);

        int r3 = solution.divide(2147483647, 1);
        System.out.println((r3 == 2147483647) + " : " + r3);

        int r4 = solution.divide(2147483647, 2);
        System.out.println((r4 == 1073741823) + " : " + r4);
    }
}

30. Substring with Concatenation of All Words

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

Example 1:

Input:
  s = "barfoothefoobarman",
*  words = ["foo","bar"]
*Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.

Example 2:

Input:
  s = "wordgoodgoodgoodbestword",
*  words = ["word","good","best","word"]
*Output: []
1
Unresolved directive in 0030-substring-with-concatenation-of-all-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0030_SubstringWithConcatenationOfAllWords.java[]

31. Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,31,3,2

3,2,11,2,3

1,1,51,5,1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 31. Next Permutation
 *
 * https://leetcode.com/problems/next-permutation/description/[Next Permutation - LeetCode]
 *
 * Implement *next permutation*, which rearranges numbers into the
 * lexicographically next greater permutation of numbers.
 *
 * If such arrangement is not possible, it must rearrange it as the lowest
 * possible order (ie, sorted in ascending order).
 *
 * The replacement must be
 * *https://en.wikipedia.org/wiki/In-place_algorithm[in-place]* and use only
 * constant extra memory.
 *
 * Here are some examples. Inputs are in the left-hand column and its corresponding
 * outputs are in the right-hand column.
 *
 * `1,2,3` → `1,3,2` +
 * `3,2,1` → `1,2,3` +
 * `1,1,5` → `1,5,1`
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-15 01:12
 */
public class _0031_NextPermutation {
    public static void nextPermutation(int[] nums) {
        if (nums == null || nums.length < 2) {
            return;
        }

        for (int i = nums.length - 1; i > 0; i--) {
            if (nums[i - 1] < nums[i]) {
                int temp = nums[i - 1];
                nums[i - 1] = nums[i];
                nums[i] = temp;
                return;
            }
        }
        Arrays.sort(nums);
    }

    public static void main(String[] args) {
        int[] a1 = new int[]{1, 2, 3};
        nextPermutation(a1);
        System.out.println(Arrays.toString(a1));


        int[] a2 = new int[]{3, 2, 1};
        nextPermutation(a2);
        assert !Objects.equals(a2, new int[]{1, 2, 3});
        System.out.println(Arrays.toString(a2));

        int[] a3 = new int[]{1, 1, 5};
        nextPermutation(a3);
        assert !Objects.equals(a3, new int[]{1, 5, 1});
        System.out.println(Arrays.toString(a3));

        int[] a4 = new int[]{1, 3, 2};
        nextPermutation(a4);
        assert !Objects.deepEquals(a4, new int[]{2, 1, 3});
        System.out.println(Arrays.toString(a4));
    }
}

32. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is "()()"
1
Unresolved directive in 0032-longest-valid-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0032_LongestValidParentheses.java[]

33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package com.diguage.algorithm.leetcode;

/**
 * = 33. Search in Rotated Sorted Array
 *
 * https://leetcode.com/problems/search-in-rotated-sorted-array/description/[Search in Rotated Sorted Array - LeetCode]
 *
 * Suppose an array sorted in ascending order is rotated at some pivot unknown
 * to you beforehand.
 *
 * (i.e., `[0,1,2,4,5,6,7]` might become `[4,5,6,7,0,1,2]`).
 *
 * You are given a target value to search. If found in the array return its
 * index, otherwise return `-1`.
 *
 * You may assume no duplicate exists in the array.
 *
 * Your algorithm's runtime complexity must be in the order of O(log n).
 *
 * .Example 1:
 * [source]
 * ----
 * Input: nums = [4,5,6,7,0,1,2], target = 0
 * Output: 4
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [4,5,6,7,0,1,2], target = 3
 * Output: -1
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-09-16 17:45
 */
public class _0033_SearchInRotatedSortedArray {
    public static int search(int[] nums, int target) {
        int result = -1;
        if (null == nums || nums.length == 0) {
            return result;
        }
        int firstNum = nums[0];
        int lastNum = nums[nums.length - 1];
        int separator = -1;
        if (firstNum > lastNum) {
            int head = 0;
            int tail = nums.length - 1;
            while (head <= tail) {
                int mid = head + (tail - head) / 2;
                int midNum = nums[mid];
                if (midNum > nums[mid + 1]) {
                    separator = mid;
                    break;
                }
                if (midNum >= firstNum) {
                    head = mid + 1;
                }
                if (midNum < lastNum) {
                    tail = mid - 1;
                }
            }
        }
        if (separator == -1) {
            return binarySearch(nums, target, 0, nums.length - 1);
        } else {
            if (firstNum <= target && target <= nums[separator]) {
                return binarySearch(nums, target, 0, separator);
            } else {
                return binarySearch(nums, target, separator + 1, nums.length - 1);
            }
        }
    }

    private static int binarySearch(int[] nums, int target, int headIndex, int tailIndex) {
        int head = headIndex;
        int tail = tailIndex;
        while (head <= tail) {
            int mid = head + (tail - head) / 2;
            int midNum = nums[mid];
            if (midNum == target) {
                return mid;
            }
            if (target <= midNum) {
                tail = mid - 1;
            }
            if (midNum < target) {
                head = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
//        int[] nums = new int[]{4, 5, 6, 7, 0, 1, 2};
//        int target = 0;

//        int[] nums = new int[]{4, 5, 6, 7, 0, 1, 2};
//        int target = 3;

//        int[] nums = new int[]{1};
//        int target = 1;

//        int[] nums = new int[]{1};
//        int target = 0;

//        int[] nums = new int[]{1, 3};
//        int target = 0;

//        int[] nums = new int[]{3, 1};
//        int target = 1;

        int[] nums = new int[]{4, 5, 1, 2, 3};
        int target = 1;
        System.out.println(search(nums, target));
    }
}

34. Find First and Last Position of Element in Sorted Array

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * == 34. Find First and Last Position of Element in Sorted Array
 *
 * https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/[Find First and Last Position of Element in Sorted Array - LeetCode]
 *
 * Given an array of integers `nums` sorted in ascending order, find the
 * starting and ending position of a given `target` value.
 *
 * Your algorithm's runtime complexity must be in the order of O(log n).
 *
 * If the target is not found in the array, return `[-1, -1]`.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: nums = [5,7,7,8,8,10], target = 8
 * Output: [3,4]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [5,7,7,8,8,10], target = 6
 * Output: [-1,-1]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-09-16 20:50
 */
public class _0034_FindFirstAndLastPositionOfElementInSortedArray {
    public static int[] searchRange(int[] nums, int target) {
        int[] result = new int[]{-1, -1};
        if (null == nums || nums.length == 0) {
            return result;
        }
        int low = 0;
        int high = nums.length - 1;
        int index = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            int midNum = nums[mid];
            if (midNum == target) {
                index = mid;
                break;
            }
            if (target <= midNum) {
                high = mid - 1;
            }
            if (midNum < target) {
                low = mid + 1;
            }
        }
        if (index < 0) {
            return result;
        }
        int startIndex = index;
        while (startIndex >= 0 && nums[startIndex] == target) {
            startIndex--;
        }
        result[0] = startIndex + 1;

        int endIndex = index;
        while (endIndex < nums.length && nums[endIndex] == target) {
            endIndex++;
        }
        result[1] = endIndex - 1;
        return result;
    }

    public static void main(String[] args) {
//        int[] nums = new int[]{5, 7, 7, 8, 8, 10};
//        int target = 8;

        int[] nums = new int[]{1};
        int target = 1;

        System.out.println(Arrays.toString(searchRange(nums, target)));
    }
}

35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.diguage.algorithm.leetcode;

/**
 * = 35. Search Insert Position
 *
 * https://leetcode.com/problems/search-insert-position/description/[Search Insert Position - LeetCode]
 *
 * Given a sorted array and a target value, return the index if the target is
 * found. If not, return the index where it would be if it were inserted in order.
 *
 * You may assume no duplicates in the array.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,3,5,6], 5
 * Output: 2
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [1,3,5,6], 2
 * Output: 1
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [1,3,5,6], 7
 * Output: 4
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: [1,3,5,6], 0
 * Output: 0
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-09-16 21:32
 */
public class _0035_SearchInsertPosition {
    public static int searchInsert(int[] nums, int target) {
        if (null == nums || nums.length == 0) {
            return 0;
        }

        if (target <= nums[0]) {
            return 0;
        }

        if (target > nums[nums.length - 1]) {
            return nums.length;
        }

        int result = -1;
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            int midNum = nums[mid];
            if (midNum >= target
                && ((mid - 1) >= 0) && nums[mid - 1] < target) {
                result = mid;
                break;
            }
            if ((mid - 1 >= 0) && target <= nums[mid - 1]) {
                high = mid - 1;
            }
            if (midNum < target) {
                low = mid + 1;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 5, 6};
        int target = 5;
        System.out.println(searchInsert(nums, target));
    }
}

36. Valid Sudoku

0036 valid sudoku

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  • Each row must contain the digits 1-9 without repetition.

  • Each column must contain the digits 1-9 without repetition.

  • Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

250px Sudoku by L2G 20050714.svg

A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Example 2:

Input:
[
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being
    modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.

  • Only the filled cells need to be validated according to the mentioned rules.

  • The given board contain only digits 1-9 and the character '.'.

  • The given board size is always 9x9.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package com.diguage.algorithm.leetcode;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * = 36. Valid Sudoku
 *
 * https://leetcode.com/problems/valid-sudoku/[Valid Sudoku - LeetCode]
 *
 * Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated *according to the following rules:*
 *
 * . Each row must contain the digits `1-9` without repetition.
 * . Each column must contain the digits `1-9` without repetition.
 * . Each of the 9 3x3 sub-boxes of the grid must contain the digits `1-9` without repetition.
 *
 * The Sudoku board could be partially filled, where empty cells are filled with the character `'.'`.
 *
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input:
 * [
 *   ["5","3",".",".","7",".",".",".","."],
 *   ["6",".",".","1","9","5",".",".","."],
 *   [".","9","8",".",".",".",".","6","."],
 *   ["8",".",".",".","6",".",".",".","3"],
 *   ["4",".",".","8",".","3",".",".","1"],
 *   ["7",".",".",".","2",".",".",".","6"],
 *   [".","6",".",".",".",".","2","8","."],
 *   [".",".",".","4","1","9",".",".","5"],
 *   [".",".",".",".","8",".",".","7","9"]
 * ]
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * [
 *   ["8","3",".",".","7",".",".",".","."],
 *   ["6",".",".","1","9","5",".",".","."],
 *   [".","9","8",".",".",".",".","6","."],
 *   ["8",".",".",".","6",".",".",".","3"],
 *   ["4",".",".","8",".","3",".",".","1"],
 *   ["7",".",".",".","2",".",".",".","6"],
 *   [".","6",".",".",".",".","2","8","."],
 *   [".",".",".","4","1","9",".",".","5"],
 *   [".",".",".",".","8",".",".","7","9"]
 * ]
 * Output: false
 * Explanation: Same as Example 1, except with the 5 in the top left corner being
 *     modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
 * ----
 *
 * *Note:*
 *
 * * A Sudoku board (partially filled) could be valid but is not necessarily solvable.
 * * Only the filled cells need to be validated according to the mentioned rules.
 * * The given board contain only digits `1-9` and the character `'.'`.
 * * The given board size is always 9x9.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-06 12:24
 */
public class _0036_ValidSudoku {
    /**
     * Runtime: 5 ms, faster than 21.21% of Java online submissions for Valid Sudoku.
     *
     * Memory Usage: 43.2 MB, less than 95.65% of Java online submissions for Valid Sudoku.
     *
     * Copy from: https://leetcode.com/problems/valid-sudoku/discuss/15472/Short%2BSimple-Java-using-Strings[Short+Simple Java using Strings - LeetCode Discuss]
     */
    public boolean isValidSudoku(char[][] board) {
        Set<String> numbers = new HashSet<>(board.length * board.length);
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[y].length; x++) {
                if (!Objects.equals(board[y][x], '.')) {
                    String value = "(" + board[y][x] + ")";
                    if (!numbers.add(y + value)
                            || !numbers.add(value + x)
                            || !numbers.add(y / 3 + value + x / 3)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        _0036_ValidSudoku solution = new _0036_ValidSudoku();
        char[][] b1 = {
                {'5', '3', '.', '.', '7', '.', '.', '.', '.'},
                {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
                {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
                {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
                {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
                {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
                {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
                {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
                {'.', '.', '.', '.', '8', '.', '.', '7', '9'}
        };
        boolean r1 = solution.isValidSudoku(b1);
        System.out.println(r1);

        char[][] b2 = {
                {'8', '3', '.', '.', '7', '.', '.', '.', '.'},
                {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
                {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
                {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
                {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
                {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
                {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
                {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
                {'.', '.', '.', '.', '8', '.', '.', '7', '9'}
        };
        boolean r2 = solution.isValidSudoku(b2);
        System.out.println(!r2);
    }
}

37. Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  • Each of the digits 1-9 must occur exactly once in each row.

  • Each of the digits 1-9 must occur exactly once in each column.

  • Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.

0037 1

A sudoku puzzle…​

0037 2

…​and its solution numbers marked in red.

Note:

  • The given board contain only digits 1-9 and the character '.'.

  • You may assume that the given Sudoku puzzle will have a single unique solution.

  • The given board size is always 9x9.

解题分析

这道题特别需要关注的点是:只要找到一个解就可以了,不需要求全部解。所以,需要重点思考的是,如何在找到第一个解时,就立即停止搜索。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.PrintUtils;

/**
 * = 37. Sudoku Solver
 *
 * https://leetcode.com/problems/sudoku-solver/[(5) Sudoku Solver - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-03-25 09:34
 */
public class _0037_SudokuSolver {
    public void solveSudoku(char[][] board) {
        backtrack(board, 0);
    }

    /**
     * Runtime: 17 ms, faster than 35.23% of Java online submissions for Sudoku Solver.
     * Memory Usage: 37 MB, less than 21.05% of Java online submissions for Sudoku Solver.
     */
    private boolean backtrack(char[][] board, int step) {
        int len = board.length;
        if (step == len * len) {
            return true;
        }
        int y = step / len;
        int x = step % len;

        for (int i = y; i < len; i++) {
            for (int j = x; j < len; j++) {
                if (board[i][j] != '.') {
                    return backtrack(board, step + 1);
                }
                for (char c = '1'; c <= '9'; c++) {
                    if (!isValid(board, i, j, c)) {
                        continue;
                    }
                    board[i][j] = c;
                    System.out.printf("y=%d,x=%d, num=%s, step=%d %n",
                            y, x, c, step);
                    PrintUtils.printMatrix(board);
                    if (backtrack(board, step + 1)) {
                        return true;
                    }
                    board[i][j] = '.';
                }
                return false;
            }
        }
        return false;
    }

    private boolean isValid(char[][] board, int y, int x, char c) {
        for (int i = 0; i < 9; i++) {
            if (board[(y / 3) * 3 + i / 3][(x / 3) * 3 + i % 3] == c
                    || board[y][i] == c
                    || board[i][x] == c) {
                return false;
            }
        }
        return true;
    }

    /**
     * Copy From
     */
    private boolean backtrackXY(char[][] board, int y, int x) {
        int len = board.length;
        if (x == len) {
            return backtrackXY(board, y + 1, 0);
        }
        if (y == len) {
            return true;
        }
        for (int i = y; i < len; i++) {
            for (int j = x; j < len; j++) {
                if (board[i][j] != '.') {
                    return backtrackXY(board, i, j + 1);
                }
                for (char c = '1'; c <= '9'; c++) {
                    if (!isValid(board, i, j, c)) {
                        continue;
                    }
                    board[i][j] = c;
                    System.out.printf("y=%d,x=%d, num=%s %n", i, j, c);
                    PrintUtils.printMatrix(board);
                    if (backtrackXY(board, i, j + 1)) {
                        return true;
                    }
                    board[i][j] = '.';
                }
                return false;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        char[][] b1 = {
                {'5', '3', '.', '.', '7', '.', '.', '.', '.'},
                {'6', '.', '.', '1', '9', '5', '.', '.', '.'},
                {'.', '9', '8', '.', '.', '.', '.', '6', '.'},
                {'8', '.', '.', '.', '6', '.', '.', '.', '3'},
                {'4', '.', '.', '8', '.', '3', '.', '.', '1'},
                {'7', '.', '.', '.', '2', '.', '.', '.', '6'},
                {'.', '6', '.', '.', '.', '.', '2', '8', '.'},
                {'.', '.', '.', '4', '1', '9', '.', '.', '5'},
                {'.', '.', '.', '.', '8', '.', '.', '7', '9'}
        };
        _0037_SudokuSolver solution = new _0037_SudokuSolver();
        PrintUtils.printMatrix(b1);
        solution.solveSudoku(b1);
        PrintUtils.printMatrix(b1);
    }
}

38. Count and Say

看懂了这道题,相声就已经入门了……

Matrix67 的解释 Conway常数是怎么得来的? | Matrix67: The Aha Moments 还是非常浅显易懂的!

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 is read off as "one 1" or 11.

11 is read off as "two 1s" or 21.

21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 38. Count and Say
 *
 * The count-and-say sequence is the sequence of integers with the first five terms as following:
 *
 * ----
 * 1.     1
 * 2.     11
 * 3.     21
 * 4.     1211
 * 5.     111221
 * ----
 *
 * `1` is read off as "`one 1`" or `11`.+
 * `11` is read off as "`two 1s`" or `21`.+
 * `21` is read off as "`one 2`, then `one 1`" or `1211`.+
 *
 * Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
 *
 * Note: Each term of the sequence of integers will be represented as a string.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 1
 * Output: "1"
 * Explanation: This is the base case.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 4
 * Output: "1211"
 * Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-17 23:16
 */
public class _0038_CountAndSay {
    /**
     * Runtime: 3 ms, faster than 40.24% of Java online submissions for Count and Say.
     *
     * Memory Usage: 40.9 MB, less than 5.26% of Java online submissions for Count and Say.
     */
    public String countAndSay(int n) {
        String result = "1";
        if (n == 1) {
            return result;
        }
        StringBuilder builder;
        for (int i = 1; i < n; i++) {
            builder = new StringBuilder();
            char[] chars = result.toCharArray();
            Character prefix = null;
            int count = 0;
            for (int j = 0; j < chars.length; j++) {
                char current = chars[j];
                if (Objects.isNull(prefix)) {
                    prefix = current;
                    ++count;
                } else {
                    if (Objects.equals(prefix, current)) {
                        ++count;
                    } else {
                        builder.append(count).append(prefix);
                        prefix = current;
                        count = 1;
                    }
                }
                if (j == chars.length - 1) {
                    builder.append(count).append(prefix);
                }
            }
            result = builder.toString();
        }

        return result;
    }

    public static void main(String[] args) {
        _0038_CountAndSay solution = new _0038_CountAndSay();
        String r1 = solution.countAndSay(5);
        System.out.println(r1.equals("111221") + " : " + r1);
    }
}

39. Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

参考 46. Permutations 认真学习一下回溯思想。

0039 1
0039 2
0039 3

思考题:如何做剪枝?这道题通过做剪枝从 164ms 优化到了 9ms。

参考资料

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [2,3,6,7], `target = `7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5]`, `target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * = 39. Combination Sum
 * <p>
 * https://leetcode.com/problems/combination-sum/description/[Combination Sum - LeetCode]
 * <p>
 * Given a set of candidate numbers (candidates) (without duplicates) and a
 * target number (target), find all unique combinations in candidates where
 * the candidate numbers sums to target.
 * <p>
 * The same repeated number may be chosen from candidates unlimited number of times.
 * <p>
 * *Note:*
 * <p>
 * * All numbers (including target) will be positive integers.
 * * The solution set must not contain duplicate combinations.
 * <p>
 * .Example 1:
 * [source]
 * ----
 * Input: candidates = [2,3,6,7], target = 7,
 * A solution set is:
 * [
 * [7],
 * [2,2,3]
 * ]
 * ----
 * <p>
 * .Example 2:
 * [source]
 * ----
 * Input: candidates = [2,3,5], target = 8,
 * A solution set is:
 * [
 * [2,2,2,2],
 * [2,3,3],
 * [3,5]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-09-16 21:56
 */
public class _0039_CombinationSum {
    /**
     * Runtime: 164 ms, faster than 5.05% of Java online submissions for Combination Sum.
     * Memory Usage: 45.5 MB, less than 5.19% of Java online submissions for Combination Sum.
     * <p>
     * ↓
     * <p>
     * Runtime: 9 ms, faster than 17.31% of Java online submissions for Combination Sum.
     * Memory Usage: 41 MB, less than 5.19% of Java online submissions for Combination Sum.
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (null == candidates || candidates.length == 0) {
            return Collections.emptyList();
        }
        Arrays.sort(candidates);

        List<List<Integer>> result = new ArrayList<>();
        backtrack(candidates, target, result, new ArrayList<>());
        return result;
    }

    private void backtrack(int[] candidates, int target, List<List<Integer>> result, List<Integer> current) {
        if (target == 0) {
            result.add(new ArrayList<>(current));
        }
        if (target < 0) {
            return;
        }
        for (int candidate : candidates) {
            if (!current.isEmpty() && current.get(current.size() - 1) > candidate) {
                continue;
            }
            current.add(candidate);
            backtrack(candidates, target - candidate, result, current);
            current.remove(current.size() - 1);
        }
    }

    public static void main(String[] args) {
        _0039_CombinationSum solution = new _0039_CombinationSum();
        System.out.println(solution.combinationSum(new int[]{2, 3, 6, 7}, 7));
        System.out.println(solution.combinationSum(new int[]{2, 3, 5}, 8));
    }
}

40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
0040 1
0040 2
0040 3

这道题的关键是由于候选值不能重复使用,所以需要向下传递起始位置。可以对比一下 [] 的处理上的不同之处。

思考一下解决重复值时是怎么剪枝的?

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 40. Combination Sum II
 *
 * https://leetcode.com/problems/combination-sum-ii/[Combination Sum II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 19:20
 */
public class _0040_CombinationSumII {
    /**
     * Runtime: 2 ms, faster than 100.00% of Java online submissions for Combination Sum II.
     * Memory Usage: 39.5 MB, less than 54.74% of Java online submissions for Combination Sum II.
     */
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        if (Objects.isNull(candidates) || candidates.length == 0) {
            return Collections.emptyList();
        }
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        backtrack(candidates, 0, target, result, new ArrayDeque<>());
        return new ArrayList<>(result);
    }

    private void backtrack(int[] candidates, int beginIndex, int target,
                           List<List<Integer>> result, Deque<Integer> current) {
        if (target == 0) {
            result.add(new ArrayList<>(current));
            return;
        }
        for (int i = beginIndex; i < candidates.length; i++) {
            int candidate = candidates[i];
            if (target < candidate) {
                break;
            }
            if (!current.isEmpty() && current.peekLast() > candidate) {
                continue;
            }
            if (beginIndex < i && candidate == candidates[i - 1]) {
                continue;
            }
            current.addLast(candidate);
            // 因为元素不可以重复使用,这里递归传递下去的是 i + 1 而不是 i
            backtrack(candidates, i + 1, target - candidate, result, current);
            current.removeLast();
        }
    }

    public static void main(String[] args) {
        _0040_CombinationSumII solution = new _0040_CombinationSumII();
        int[] c3 = {1, 2};
        System.out.println(solution.combinationSum2(c3, 4));

        int[] c1 = {10, 1, 2, 7, 6, 1, 5};
        System.out.println(solution.combinationSum2(c1, 8));

        int[] c2 = {2, 5, 2, 1, 2};
        System.out.println(solution.combinationSum2(c2, 5));
    }
}

41. First Missing Positive

这道题跟 268. Missing Number - LeetCode 很像!

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 41. First Missing Positive
 *
 * https://leetcode.com/problems/first-missing-positive/[First Missing Positive - LeetCode]
 *
 * Given an unsorted integer array, find the smallest missing positive integer.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,2,0]
 * Output: 3
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [3,4,-1,1]
 * Output: 2
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [7,8,9,11,12]
 * Output: 1
 * ----
 *
 * *Note:*
 *
 * Your algorithm should run in O(n) time and uses constant extra space.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-23 12:54:29
 */
public class _0041_FirstMissingPositive {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for First Missing Positive.
     *
     * Memory Usage: 34.6 MB, less than 100.00% of Java online submissions for First Missing Positive.
     */
    public int firstMissingPositive(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 1;
        }
        int length = nums.length;
        for (int i = 0; i < length; ) {
            int iNum = nums[i];
            if (0 < iNum && iNum <= length && nums[iNum - 1] != iNum) {
                swap(nums, i, iNum - 1);
            } else {
                i++;
            }
        }
        int i = 0;
        while (i < length && nums[i] == i + 1) {
            i++;
        }

        return i + 1;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        _0041_FirstMissingPositive solution = new _0041_FirstMissingPositive();
        int i1 = solution.firstMissingPositive(new int[]{1, 2, 0});
        System.out.println((i1 == 3) + ", " + i1);

        int i2 = solution.firstMissingPositive(new int[]{3, 4, -1, 1});
        System.out.println((i2 == 2) + ", " + i2);

        int i3 = solution.firstMissingPositive(new int[]{7, 8, 9, 11, 12});
        System.out.println((i3 == 1) + ", " + i3);
    }
}

42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

rainwatertrap

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

解题分析

有点懵逼,没看太明白。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.diguage.algorithm.leetcode;

/**
 * = 42. Trapping Rain Water
 *
 * https://leetcode.com/problems/trapping-rain-water/[Trapping Rain Water - LeetCode]
 *
 * Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
 *
 * image::https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png[title="The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!"]
 *
 * .Example:
 * [source]
 * ----
 * Input: [0,1,0,2,1,0,1,3,2,1,2,1]
 * Output: 6
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-07-26 08:49
 */
public class _0042_TrappingRainWater {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Trapping Rain Water.
     * Memory Usage: 38.3 MB, less than 91.10% of Java online submissions for Trapping Rain Water.
     *
     * Copy from: https://leetcode-cn.com/problems/trapping-rain-water/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-8/[详细通俗的思路分析,多解法 - 接雨水 - 力扣(LeetCode)]
     */
    public int trap(int[] height) {
        int left = 0, right = height.length - 1;
        int result = 0;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                if (height[left] >= leftMax) {
                    leftMax = height[left];
                } else {
                    result += (leftMax - height[left]);
                }
                ++left;
            } else {
                if (height[right] > rightMax) {
                    rightMax = height[right];
                } else {
                    result += (rightMax - height[right]);
                }
                --right;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0042_TrappingRainWater solution = new _0042_TrappingRainWater();
        int r1 = solution.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});
        System.out.println((r1 == 6) + " : " + r1);
    }
}

思考题

尝试一下动态规划解法!

43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.

  2. Both num1 and num2 contain only digits 0-9.

  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题思路

0043 1

将每次相乘的计算结果存入到一个数组中,每个元素保存一个位上的数字。

参考资料

  1. 优化版竖式(打败99.4%) - 字符串相乘 - 力扣(LeetCode) — 第二种解法,最初没看明白,但是受他们的启发,我自己想到了。

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.

  2. Both num1 and num2 contain only digits 0-9.

  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.diguage.algorithm.leetcode;

/**
 * = 43. Multiply Strings
 *
 * https://leetcode.com/problems/multiply-strings/[Multiply Strings - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-03 21:07
 */
public class _0043_MultiplyStrings {
    /**
     * Runtime: 5 ms, faster than 59.85% of Java online submissions for Multiply Strings.
     * Memory Usage: 38.5 MB, less than 16.67% of Java online submissions for Multiply Strings.
     */
    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        int[] products = new int[num1.length() + num2.length()];
        for (int i = num1.length() - 1; i >= 0; i--) {
            int iNum = num1.charAt(i) - '0';
            if (iNum == 0) {
                continue;
            }
            for (int j = num2.length() - 1; j >= 0; j--) {
                int jNum = num2.charAt(j) - '0';
                int sum = products[i + j + 1] + iNum * jNum;
                products[i + j + 1] = sum % 10;
                products[i + j] += sum / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < products.length; i++) {
            if (i == 0 && products[i] == 0) {
                continue;
            }
            sb.append(products[i]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        _0043_MultiplyStrings solution = new _0043_MultiplyStrings();
        String r5 = solution.multiply("7067", "7967");
        System.out.println("56302789".equals(r5) + " : " + r5);

        String r4 = solution.multiply("6", "501");
        System.out.println("3006".equals(r4) + " : " + r4);

        String r1 = solution.multiply("123", "456");
        System.out.println("56088".equals(r1) + " : " + r1);

        String r2 = solution.multiply("123", "4567");
        System.out.println("561741".equals(r2) + " : " + r2);

        String r3 = solution.multiply("88888888", "999999999");
        System.out.println("88888887911111112".equals(r3) + " : " + r3);
    }
}

44. Wildcard Matching

Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

Note:

  • s could be empty and contains only lowercase letters a-z.

  • p could be empty and contains only lowercase letters a-z, and characters like <font face="monospace">? or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = ""
*Output: true
Explanation: '*' matches any sequence.

Example 3:

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Example 4:

Input:
s = "adceb"
p = "a*b"
*Output: true
Explanation: The first '' matches the empty sequence, while the second '' matches the substring "dce".

Example 5:

Input:
s = "acdcb"
p = "a*c?b"
Output: false
1
Unresolved directive in 0044-wildcard-matching.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0044_WildcardMatching.java[]

45. Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 45. Jump Game II
 *
 * https://leetcode.com/problems/jump-game-ii/[Jump Game II - LeetCode]
 *
 * Given an array of non-negative integers, you are initially positioned at the first index of the array.
 *
 * Each element in the array represents your maximum jump length at that position.
 *
 * Your goal is to reach the last index in the minimum number of jumps.
 *
 * .Example:
 * [source]
 * ----
 * Input: [2,3,1,1,4]
 * Output: 2
 * Explanation: The minimum number of jumps to reach the last index is 2.
 * Jump 1 step from index 0 to 1, then 3 steps to the last index.
 * ----
 *
 * *Note:*
 *
 * You can assume that you can always reach the last index.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 11:29
 */
public class _0045_JumpGameII {
    /**
     * Runtime: 1 ms, faster than 99.98% of Java online submissions for Jump Game II.
     *
     * Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Jump Game II.
     */
    public int jump(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int step = 0;
        int currentStepEnd = 0;
        int currentFarthestIndex = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            currentFarthestIndex = Math.max(currentFarthestIndex, i + nums[i]);
            if (i == currentStepEnd) {
                step++;
                currentStepEnd = currentFarthestIndex;
            }
        }
        return step;
    }

    // TODO: Dynamic Programming

    public static void main(String[] args) {
        _0045_JumpGameII solution = new _0045_JumpGameII();
        int r1 = solution.jump(new int[]{2, 3, 1, 1, 4});
        System.out.println((r1 == 2) + " : " + r1);
    }
}

46. Permutations

首先介绍“回溯”算法的应用。“回溯”算法也叫“回溯搜索”算法,主要用于在一个庞大的空间里搜索我们所需要的问题的解。我们每天使用的“搜索引擎”就是帮助我们在庞大的互联网上搜索我们需要的信息。“搜索”引擎的“搜索”和“回溯搜索”算法的“搜索”意思是一样的。

“回溯”指的是“状态重置”,可以理解为“回到过去”、“恢复现场”,是在编码的过程中,是为了节约空间而使用的一种技巧。而回溯其实是“深度优先遍历”特有的一种现象。之所以是“深度优先遍历”,是因为我们要解决的问题通常是在一棵树上完成的,在这棵树上搜索需要的答案,一般使用深度优先遍历。

“全排列”就是一个非常经典的“回溯”算法的应用。我们知道,N 个数字的全排列一共有 N! 这么多个。

使用编程的方法得到全排列,就是在这样的一个树形结构中进行编程,具体来说,就是执行一次深度优先遍历,从树的根结点到叶子结点形成的路径就是一个全排列。

0046 1

说明:

  1. 每一个结点表示了“全排列”问题求解的不同阶段,这些阶段通过变量的“不同的值”体现;

  2. 这些变量的不同的值,也称之为“状态”;

  3. 使用深度优先遍历有“回头”的过程,在“回头”以后,状态变量需要设置成为和先前一样;

  4. 因此在回到上一层结点的过程中,需要撤销上一次选择,这个操作也称之为“状态重置”;

  5. 深度优先遍历,可以直接借助系统栈空间,为我们保存所需要的状态变量,在编码中只需要注意遍历到相应的结点的时候,状态变量的值是正确的,具体的做法是:往下走一层的时候,path 变量在尾部追加,而往回走的时候,需要撤销上一次的选择,也是在尾部操作,因此 path 变量是一个栈。

  6. 深度优先遍历通过“回溯”操作,实现了全局使用一份状态变量的效果。

解决一个回溯问题,实际上就是一个决策树的遍历过程。只需要思考 3 个问题:

  1. 路径:也就是已经做出的选择。

  2. 选择列表:也就是你当前可以做的选择。

  3. 结束条件:也就是到达决策树底层,无法再做选择的条件。

代码方面,回溯算法的框架:

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return

    for 选择 in 选择列表:
        做选择
        backtrack(路径, 选择列表)
        撤销选择

其核心就是 for 循环里面的递归,在递归调用之前「做选择」,在递归调用之后「撤销选择」,特别简单。

必须说明的是,不管怎么优化,都符合回溯框架,而且时间复杂度都不可能低于 O(N!),因为穷举整棵决策树是无法避免的。这也是回溯算法的一个特点,不像动态规划存在重叠子问题可以优化,回溯算法就是纯暴力穷举,复杂度一般都很高。

参考资料

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * = 46. Permutations
 *
 * https://leetcode.com/problems/permutations/[Permutations - LeetCode]
 *
 * Given a collection of *distinct* integers, return all possible permutations.
 *
 * .Example:
 * [source]
 * ----
 * Input: [1,2,3]
 * Output:
 * [
 *   [1,2,3],
 *   [1,3,2],
 *   [2,1,3],
 *   [2,3,1],
 *   [3,1,2],
 *   [3,2,1]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 12:35
 */
public class _0046_Permutations {
    /**
     * Runtime: 5 ms, faster than 8.40% of Java online submissions for Permutations.
     *
     * Memory Usage: 45.3 MB, less than 5.68% of Java online submissions for Permutations.
     *
     * Copy from: https://leetcode.com/problems/permutations/discuss/18239/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partioning)[A general approach to backtracking questions in Java (Subsets, Permutations, Combination Sum, Palindrome Partioning) - LeetCode Discuss]
     */
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new LinkedList<>();
        backtrack(nums, result, new ArrayList<Integer>());
        return result;
    }

    private void backtrack(int[] nums, List<List<Integer>> result, ArrayList<Integer> path) {
        if (path.size() == nums.length) {
            result.add(new ArrayList<>(path));
        } else {
            for (int i = 0; i < nums.length; i++) {
                int num = nums[i];
                if (path.contains(num)) {
                    continue;
                }
                path.add(num);
                backtrack(nums, result, path);
                path.remove(path.size() - 1);
            }
        }
    }


    public static void main(String[] args) {
        _0046_Permutations solution = new _0046_Permutations();
        int[] n1 = {1, 2, 3};
        List<List<Integer>> r1 = solution.permute(n1);
        System.out.println(Objects.toString(r1));
    }
}

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:
Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
0047 1

思考:去重剪枝的判断是怎么实现的?

参考资料

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 47. Permutations II
 *
 * https://leetcode.com/problems/permutations-ii/[Permutations II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 20:29
 */
public class _0047_PermutationsII {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Permutations II.
     * Memory Usage: 41.6 MB, less than 11.94% of Java online submissions for Permutations II.
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return Collections.emptyList();
        }
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, 0, used, result, new ArrayDeque<>());
        return result;
    }

    private void backtrack(int[] nums, int startIndex, boolean[] used,
                           List<List<Integer>> result, Deque<Integer> current) {
        if (nums.length == startIndex) {
            result.add(new ArrayList<>(current));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {

                // 修改 2:在 used[i - 1] 刚刚被撤销的时候剪枝,说明接下来会被选择,搜索一定会重复,故"剪枝"
                if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) {
                    continue;
                }

                used[i] = true;
                current.addLast(nums[i]);
                backtrack(nums, startIndex + 1, used, result, current);

                current.removeLast();
                used[i] = false;
            }
        }
    }

    public static void main(String[] args) {
        _0047_PermutationsII solution = new _0047_PermutationsII();
        int[] n1 = {1, 1, 2};
        System.out.println(solution.permuteUnique(n1));
    }
}

48. Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix =
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

Given input matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
],

rotate the input matrix in-place such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.diguage.algorithm.leetcode;

import java.util.Objects;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 48. Rotate Image
 *
 * https://leetcode.com/problems/rotate-image/[Rotate Image - LeetCode]
 *
 * You are given an n x n 2D matrix representing an image.
 *
 * Rotate the image by 90 degrees (clockwise).
 *
 * *Note:*
 *
 * You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
 *
 * .Example 1:
 * [source]
 * ----
 * Given input matrix =
 * [
 *   [1,2,3],
 *   [4,5,6],
 *   [7,8,9]
 * ],
 *
 * rotate the input matrix in-place such that it becomes:
 * [
 *   [7,4,1],
 *   [8,5,2],
 *   [9,6,3]
 * ]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Given input matrix =
 * [
 *   [ 5, 1, 9,11],
 *   [ 2, 4, 8,10],
 *   [13, 3, 6, 7],
 *   [15,14,12,16]
 * ],
 *
 * rotate the input matrix in-place such that it becomes:
 * [
 *   [15,13, 2, 5],
 *   [14, 3, 4, 1],
 *   [12, 6, 8, 9],
 *   [16, 7,10,11]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-24 00:57:55
 */
public class _0048_RotateImage {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Image.
     *
     * Memory Usage: 36.3 MB, less than 100.00% of Java online submissions for Rotate Image.
     */
    public void rotate(int[][] matrix) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return;
        }
        int length = matrix.length;
        // 先交换行,这样操作更方便,但是也会有更多的额外空间。
        for (int i = 0; i < length / 2; i++) {
            int[] temp = matrix[i];
            matrix[i] = matrix[length - 1 - i];
            matrix[length - 1 - i] = temp;
        }
//        printMatrix(matrix);
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < i; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Image.
     *
     * Memory Usage: 36.2 MB, less than 100.00% of Java online submissions for Rotate Image.
     */
    public void rotate1(int[][] matrix) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return;
        }
        int length = matrix.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < i; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        printMatrix(matrix);
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length / 2; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][length - j - 1];
                matrix[i][length - j - 1] = temp;
            }
        }
    }

    public static void main(String[] args) {
        _0048_RotateImage solution = new _0048_RotateImage();
        int[][] array1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        printMatrix(array1);
        solution.rotate(array1);
        printMatrix(array1);

        int[][] array2 = {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
        printMatrix(array2);
        solution.rotate(array2);
        printMatrix(array2);
    }
}

49. Group Anagrams

计数字符数量的解法有些精巧!这里想起来了波利亚在《怎样解题》中,着重强调的一点:一点要充分挖掘题目中的一直变量。题目中已经明确给出,所有的字符都是小写字符。但却没有意识到它的重要性!

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

  • All inputs will be in lowercase.

  • The order of your output does not matter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 49. Group Anagrams
 *
 * https://leetcode.com/problems/group-anagrams/[Group Anagrams - LeetCode]
 *
 * Given an array of strings, group anagrams together.
 *
 * .Example:
 * [source]
 * ----
 * Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
 * Output:
 * [
 *   ["ate","eat","tea"],
 *   ["nat","tan"],
 *   ["bat"]
 * ]
 * ----
 *
 * *Note:*
 *
 * * All inputs will be in lowercase.
 * * The order of your output does not matter.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-06 21:42
 */
public class _0049_GroupAnagrams {
    /**
     * Runtime: 16 ms, faster than 22.85% of Java online submissions for Group Anagrams.
     *
     * Memory Usage: 40.4 MB, less than 96.49% of Java online submissions for Group Anagrams.
     */
    public List<List<String>> groupAnagrams(String[] strs) {
        if (Objects.isNull(strs) || strs.length == 0) {
            return Collections.emptyList();
        }
        Map<String, List<String>> charsToStringsMap = new HashMap<>();
        int[] count = new int[26];
        for (String str : strs) {
            Arrays.fill(count, 0);
            char[] chars = str.toCharArray();
            for (char aChar : chars) {
                count[aChar - 'a']++;
            }
            StringBuilder builder = new StringBuilder(26 * 2);
            for (int i : count) {
                builder.append("#").append(i);
            }
            String key = builder.toString();
            List<String> strings = charsToStringsMap.getOrDefault(key, new ArrayList<>());
            strings.add(str);
            charsToStringsMap.put(key, strings);
        }
        return new ArrayList<>(charsToStringsMap.values());
    }

    /**
     * Runtime: 8 ms, faster than 96.90% of Java online submissions for Group Anagrams.
     *
     * Memory Usage: 41.1 MB, less than 95.32% of Java online submissions for Group Anagrams.
     */
    public List<List<String>> groupAnagramsSort(String[] strs) {
        if (Objects.isNull(strs) || strs.length == 0) {
            return Collections.emptyList();
        }
        Map<String, List<String>> charsToStringsMap = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> strings = charsToStringsMap.getOrDefault(key, new ArrayList<>());
            strings.add(str);
            charsToStringsMap.put(key, strings);
        }
        return new ArrayList<>(charsToStringsMap.values());
    }

    public static void main(String[] args) {
        _0049_GroupAnagrams solution = new _0049_GroupAnagrams();
        String[] s1 = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> r1 = solution.groupAnagrams(s1);
        System.out.println(Arrays.deepToString(r1.toArray()));
    }
}

50. Pow(x, n)

首先,可以把"一半的计算结果"存储起来,节省一半的递归调用;

其次,没想到还需要处理"无穷"的情况!

另外,思考一下,如果使用迭代来实现?

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0

  • n is a 32-bit signed integer, within the range [-231, 2^31 ^- 1]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.diguage.algorithm.leetcode;

/**
 * = 50. Pow(x, n)
 *
 * https://leetcode.com/problems/powx-n/[Pow(x, n) - LeetCode]
 *
 * Implement `pow(x, n)`, which calculates x raised to the power n (x^n^).
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 2.00000, 10
 * Output: 1024.00000
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 2.10000, 3
 * Output: 9.26100
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 2.00000, -2
 * Output: 0.25000
 * Explanation: 2-2 = 1/22 = 1/4 = 0.25
 * ----
 *
 * *Note:*
 *
 * * `-100.0 < x < 100.0`
 * * n is a 32-bit signed integer, within the range [−2^31^, 2^31^ − 1]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-13 21:19
 */
public class _0050_PowXN {

    /**
     * Runtime: 1 ms, faster than 94.10% of Java online submissions for Pow(x, n).
     *
     * Memory Usage: 34.4 MB, less than 5.88% of Java online submissions for Pow(x, n).
     */
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1.0;
        }
        if (n < 0) {
            x = 1 / x;
            n = -n;
        }

        double semiResult = myPow(x, n / 2);
        if (Double.isInfinite(semiResult)) {
            return 0.0;
        }

        return (n % 2 == 0 ? 1.0 : x) * semiResult * semiResult;
    }

    /**
     * Time Limit Exceeded
     * <p>
     * Copy from:
     */
    public double myPowTimeout(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n < 0) {
            x = 1 / x;
            n = -n;
        }
        return n % 2 == 0 ? myPowTimeout(x, n / 2) * myPowTimeout(x, n / 2)
                : x * myPowTimeout(x, n / 2) * myPowTimeout(x, n / 2);
    }

    public static void main(String[] args) {
        _0050_PowXN solution = new _0050_PowXN();
        double r1 = solution.myPow(2.0, -2);
        System.out.println(r1);

        double r2 = solution.myPow(2.1, 3);
        System.out.println(r2);

        double r3 = solution.myPow(-2.1, 3);
        System.out.println(r3);

        double r4 = solution.myPow(2, Integer.MIN_VALUE);
        System.out.println(r4);
    }
}

51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

0051 0 8 queens

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where Q and . both indicate a queen and an empty space respectively.

Example:
Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
 ]

Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

解题分析

八皇后问题是回溯思想的经典题目。

当在棋盘上放置了一个皇后后,立即排除当前行,列和对应的两个对角线。这里有一点可以优化:我们从上向下进行尝试,所以,只需要判断当前行以上的相关节点是否冲突即可。另外,先检查再渐进点,合适之后,再向前走,可以做到有效地剪枝。

0051 1

这里有个知识点需要注意:

对于所有的主对角线有 行号 + 列号 = 常数
对于所有的次对角线有 行号 - 列号 = 常数
如下图所示:

0051 2

利用回溯解题时,只回溯一半,然后将每个解反转即可求得另外一般解。这里有个细节需要注意:如果长度是奇数,而且第一行中间是合法位置,则在回溯过程中已经产生了对称解法。就不需要再反转了。

参考资料

The n-queens puzzle is the problem of placing n queens on an n×_n_ chessboard such that no two queens attack each other.

8 queens

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 51. N-Queens
 *
 * [N-Queens - LeetCode](https://leetcode.com/problems/n-queens/)
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 12:55
 */
public class _0051_NQueens {
    /**
     * Runtime: 4 ms, faster than 64.59% of Java online submissions for N-Queens.
     * Memory Usage: 41.3 MB, less than 5.41% of Java online submissions for N-Queens.
     */
    public List<List<String>> solveNQueens(int n) {
        int[][] matrix = new int[n][n];
        List<List<String>> result = new ArrayList<>();
        backtrack(matrix, 0, 0, result);
        int size = result.size();
        if (size == 0) {
            return result;
        }
        for (int i = 0; i < size; i++) {
            List<String> om = result.get(i);
            // 如果长度是奇数,而且第一行中间是合法位置,则在回溯过程中已经产生了对称解法。
            if (!(n % 2 == 1 && om.get(0).charAt(getMid(n)) == 'Q')) {
                List<String> nm = reverseMatrix(om);
                result.add(nm);
            }
        }
        return result;
    }

    private List<String> reverseMatrix(List<String> matrix) {
        List<String> result = new ArrayList<>(matrix.size());
        for (String s : matrix) {
            StringBuilder sb = new StringBuilder(s);
            result.add(sb.reverse().toString());
        }
        return result;
    }

    private void backtrack(int[][] matrix, int y, int step, List<List<String>> result) {
        int length = matrix.length;
        if (step == length) {
            result.add(matrixToList(matrix));
            return;
        }
        for (int xi = 0; xi < length; xi++) {
            if (y == 0) {
                int mid = getMid(length);
                if (mid < xi) {
                    break;
                }
            }
            if (isValid(matrix, y, xi)) {
                matrix[y][xi] = 1;
                backtrack(matrix, y + 1, step + 1, result);
                matrix[y][xi] = 0;
            }
        }
    }

    private int getMid(int length) {
        return length % 2 == 0 ? length / 2 - 1 : length / 2;
    }

    private List<String> matrixToList(int[][] matrix) {
        List<String> result = new ArrayList<>(matrix.length);
        for (int y = 0; y < matrix.length; y++) {
            StringBuilder sb = new StringBuilder();
            for (int x = 0; x < matrix[0].length; x++) {
                if (matrix[y][x] == 0) {
                    sb.append(".");
                } else {
                    sb.append("Q");
                }
            }
            result.add(sb.toString());
        }
        return result;
    }

    private boolean isValid(int[][] matrix, int y, int x) {
        int len = matrix.length;
        // 同列
        for (int i = 0; i < y; i++) {
            if (matrix[i][x] == 1) {
                return false;
            }
        }
//        // 同行
//        for (int i = 0; i < len; i++) {
//            if (i != x && matrix[y][i] == 1) {
//                return false;
//            }
//        }
        // 左上角
        for (int i = 1; i < len && y - i >= 0 && x - i >= 0; i++) {
            if (matrix[y - i][x - i] == 1) {
                return false;
            }
        }
        // 右上角:从右上角到最下角的对角线,他们 "行号 + 列号 = 常数"
        int sum = x + y;
        for (int yi = y - 1; yi >= 0 && 0 <= sum - yi && sum - yi < len; yi--) {
            if (matrix[yi][sum - yi] == 1) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        _0051_NQueens solution = new _0051_NQueens();

        List<List<String>> r1 = solution.solveNQueens(14);
        printMatrix(r1);
    }
}

52. N-Queens II

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

0052 8 queens

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

解题分析

解题分析参考 N-Queens

The n-queens puzzle is the problem of placing n queens on an n×_n_ chessboard such that no two queens attack each other.

8 queens

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.diguage.algorithm.leetcode;

/**
 * = 52. N-Queens II
 *
 * https://leetcode.com/problems/n-queens-ii/[N-Queens II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 16:25
 */
public class _0052_NQueensII {
    /**
     * Runtime: 1 ms, faster than 95.68% of Java online submissions for N-Queens II.
     * Memory Usage: 36 MB, less than 8.70% of Java online submissions for N-Queens II.
     */
    private int result = 0;
    public int totalNQueens(int n) {
        int[][] matrix = new int[n][n];
        backtrack(matrix, 0, 0);
        return result;
    }

    private void backtrack(int[][] matrix, int y, int step) {
        if (step == matrix.length) {
            result++;
            return;
        }
        for (int xi = 0; xi < matrix[0].length; xi++) {
            if (isValid(matrix, y, xi)) {
                matrix[y][xi] = 1;
                backtrack(matrix, y + 1, step + 1);
                matrix[y][xi] = 0;
            }
        }
    }

    private boolean isValid(int[][] matrix, int y, int x) {
        int len = matrix.length;
        // 同列
        for (int i = 0; i < y; i++) {
            if (matrix[i][x] == 1) {
                return false;
            }
        }
        // 左上角
        for (int i = 1; i < len && y - i >= 0 && x - i >= 0; i++) {
            if (matrix[y - i][x - i] == 1) {
                return false;
            }
        }
        // 右上角:从右上角到最下角的对角线,他们 "行号 + 列号 = 常数"
        int sum = x + y;
        for (int yi = y - 1; yi >= 0 && 0 <= sum - yi && sum - yi < len; yi--) {
            if (matrix[yi][sum - yi] == 1) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        _0052_NQueensII solution = new _0052_NQueensII();
        int r1 = solution.totalNQueens(4);
        System.out.println((r1 == 2) + " : " + r1);
    }
}

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 53. Maximum Subarray
 *
 * https://leetcode.com/problems/maximum-subarray/[Maximum Subarray - LeetCode]
 *
 * Given an integer array nums, find the contiguous subarray (containing at least
 * one number) which has the largest sum and return its sum.
 *
 * .Example:
 * [source]
 * ----
 * Input: [-2,1,-3,4,-1,2,1,-5,4],
 * Output: 6
 * Explanation: [4,-1,2,1] has the largest sum = 6.
 * ----
 *
 * *Follow up:*
 *
 * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-23 11:47
 */
public class _0053_MaximumSubarray {
    public int maxSubArrayDP(int[] nums) {
        // TODO Dynamic Programming
        // TODO Divide and Conquer
        return 0;
    }
    /**
     * Runtime: 1 ms, faster than 86.91% of Java online submissions for Maximum Subarray.
     *
     * Memory Usage: 42.1 MB, less than 5.16% of Java online submissions for Maximum Subarray.
     */
    public int maxSubArray(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int largestSum = nums[0];
        int largestEndingHere = nums[0];
        for (int i = 1; i < nums.length; i++) {
            largestEndingHere = Math.max(largestEndingHere + nums[i], nums[i]);
            largestSum = Math.max(largestSum, largestEndingHere);
        }
        return largestSum;
    }

    public static void main(String[] args) {
        _0053_MaximumSubarray solution = new _0053_MaximumSubarray();
        int r1 = solution.maxSubArray(new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4});
        System.out.println((r1 == 6) + " : " + r1);
    }
}

54. Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 54. Spiral Matrix
 *
 * https://leetcode.com/problems/spiral-matrix/[Spiral Matrix - LeetCode]
 *
 * Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
 *
 * .Example 1:
 * [source]
 * ----
 * Input:
 * [
 *   [ 1, 2, 3 ],
 *   [ 4, 5, 6 ],
 *   [ 7, 8, 9 ]
 * ]
 * Output: [1,2,3,6,9,8,7,4,5]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * [
 *   [1, 2, 3, 4],
 *   [5, 6, 7, 8],
 *   [9,10,11,12]
 * ]
 * Output: [1,2,3,4,8,12,11,10,9,5,6,7]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 00:51:20
 */
public class _0054_SpiralMatrix {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Spiral Matrix.
     *
     * Memory Usage: 34.4 MB, less than 100.00% of Java online submissions for Spiral Matrix.
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return Collections.emptyList();
        }
        int xLength = matrix.length;
        int yLength = matrix[0].length;
        List<Integer> result = new ArrayList<>(xLength * yLength);
        int r1 = 0, r2 = matrix.length - 1;
        int c1 = 0, c2 = matrix[0].length - 1;
        while (r1 <= r2 && c1 <= c2) {
            for (int c = c1; c <= c2; c++) {
                result.add(matrix[r1][c]);
            }
            for (int r = r1 + 1; r <= r2; r++) {
                result.add(matrix[r][c2]);
            }
            if (r1 < r2 && c1 < c2) {
                for (int c = c2 - 1; c > c1; c--) {
                    result.add(matrix[r2][c]);
                }
                for (int r = r2; r > r1; r--) {
                    result.add(matrix[r][c1]);
                }
            }
            r1++;
            r2--;
            c1++;
            c2--;
        }
        return result;
    }

    public static void main(String[] args) {
        _0054_SpiralMatrix solution = new _0054_SpiralMatrix();

        int[][] array1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        List<Integer> r1 = solution.spiralOrder(array1);
        System.out.println(Arrays.asList(1, 2, 3, 6, 9, 8, 7, 4, 5).equals(r1)
                + " : " + Arrays.toString(r1.toArray()));

        int[][] array2 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> r2 = solution.spiralOrder(array2);
        System.out.println(Arrays.asList(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7).equals(r2)
                + " : " + Arrays.toString(r2.toArray()));
    }
}

55. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 55. Jump Game
 *
 * https://leetcode.com/problems/jump-game/[Jump Game - LeetCode]
 *
 * Given an array of non-negative integers, you are initially positioned at the first index of the array.
 *
 * Each element in the array represents your maximum jump length at that position.
 *
 * Determine if you are able to reach the last index.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [2,3,1,1,4]
 * Output: true
 * Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [3,2,1,0,4]
 * Output: false
 * Explanation: You will always arrive at index 3 no matter what. Its maximum
 * jump length is 0, which makes it impossible to reach the last index.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-23 12:25
 */
public class _0055_JumpGame {
    /**
     * Runtime: 1 ms, faster than 99.35% of Java online submissions for Jump Game.
     *
     * Memory Usage: 37.7 MB, less than 100.00% of Java online submissions for Jump Game.
     */
    public boolean canJump(int[] nums) {
        if (Objects.isNull(nums) || nums.length <= 1) {
            return true;
        }
        int lenght = nums.length;
        int tail = lenght - 1;
        for (int i = tail - 1; i >= 0; i--) {
            if (nums[i] >= tail - i || nums[i] >= lenght - 1 - i) {
                tail = i;
            }
        }

        return tail <= 0;
    }

    // TODO: Backtracking
    // TODO: Dynamic Programming Top-down
    // TODO: Dynamic Programming Bottom-up

    public static void main(String[] args) {
        _0055_JumpGame solution = new _0055_JumpGame();
        boolean r1 = solution.canJump(new int[]{2, 3, 1, 1, 4});
        System.out.println(r1);

        boolean r2 = solution.canJump(new int[]{3, 2, 1, 0, 4});
        System.out.println(r2);

        boolean r3 = solution.canJump(new int[]{2, 0});
        System.out.println(r3);

        boolean r4 = solution.canJump(new int[]{2, 5, 0, 0});
        System.out.println(r4);
    }
}

56. Merge Intervals

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Example 2:

Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 56. Merge Intervals
 *
 * https://leetcode.com/problems/merge-intervals/[Merge Intervals - LeetCode]
 *
 * Given a collection of intervals, merge all overlapping intervals.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [[1,3],[2,6],[8,10],[15,18]]
 * Output: [[1,6],[8,10],[15,18]]
 * Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [[1,4],[4,5]]
 * Output: [[1,5]]
 * Explanation: Intervals [1,4] and [4,5] are considered overlapping.
 * ----
 *
 * *NOTE:* input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-23 12:27
 */
public class _0056_MergeIntervals {
    public int[][] merge(int[][] intervals) {
        if (Objects.isNull(intervals) || intervals.length <= 1) {
            return intervals;
        }
        Arrays.sort(intervals, Comparator.comparingInt(o -> o[0]));
        int index = 0;
        for (int i = 1; i < intervals.length; i++) {
            if (index < 0 || intervals[index][1] < intervals[i][0]) {
                intervals[index + 1] = intervals[i];
                index++;
            } else {
                intervals[index][1] = Math.max(intervals[i][1], intervals[index][1]);
            }
        }
        return Arrays.copyOf(intervals, index + 1);
    }

    public static void main(String[] args) {
        _0056_MergeIntervals solution = new _0056_MergeIntervals();
        int[][] matrix = {{8, 10}, {2, 6}, {15, 18}, {1, 3}};
        printMatrix(matrix);
        int[][] r1 = solution.merge(matrix);
        printMatrix(r1);

        int[][] matrix2 = {{1, 4}, {4, 5}};
        printMatrix(matrix2);
        int[][] r2 = solution.merge(matrix2);
        printMatrix(r2);

        int[][] matrix3 = {{1, 9}, {2, 5}, {19, 20}, {10, 11}, {12, 20}, {0, 3}, {0, 1}, {0, 2}};
        printMatrix(matrix3);
        int[][] r3 = solution.merge(matrix3);
        printMatrix(r3);
    }
}

57. Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1
Unresolved directive in 0057-insert-interval.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0057_InsertInterval.java[]

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:
Input: "Hello World"
Output: 5

代码还是要力求简洁明了!

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 58. Length of Last Word
 * <p>
 * https://leetcode.com/problems/length-of-last-word/[Length of Last Word - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-01 22:49
 */
public class _0058_LengthOfLastWord {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
     * Memory Usage: 38 MB, less than 7.57% of Java online submissions for Length of Last Word.
     *
     * Copy from: https://leetcode-cn.com/problems/length-of-last-word/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/[画解算法:58. 最后一个单词的长度 - 最后一个单词的长度 - 力扣(LeetCode)]
     */
    public int lengthOfLastWord(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return 0;
        }
        int end = s.length() - 1;
        while (end >= 0 && s.charAt(end) == ' ') {
            end--;
        }
        if (end < 0) {
            return 0;
        }
        int start = end;
        while (start >= 0 && s.charAt(start) != ' ') {
            start--;
        }
        return end - start;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Length of Last Word.
     * Memory Usage: 37.3 MB, less than 48.48% of Java online submissions for Length of Last Word.
     */
    public int lengthOfLastWordFor(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return 0;
        }
        int start = s.length(), end = s.length();
        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (end == s.length() && c != ' ') {
                end = i;
            }
            if (c == ' ' && i < end && end != s.length()) {
                start = i;
                break;
            }
        }
        if (start == s.length() && end != s.length()) {
            start = -1;
        }
        return end - start;
    }

    public static void main(String[] args) {
        _0058_LengthOfLastWord solution = new _0058_LengthOfLastWord();
        int r1 = solution.lengthOfLastWord("Hello World");
        System.out.println((r1 == 5) + " : " + r1);
    }
}

59. Spiral Matrix II

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.diguage.algorithm.leetcode;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 59. Spiral Matrix II
 *
 * https://leetcode.com/problems/spiral-matrix-ii/[Spiral Matrix II - LeetCode]
 *
 * Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
 *
 * .Example:
 * [source]
 * ----
 * Input: 3
 * Output:
 * [
 *   [ 1, 2, 3 ],
 *   [ 8, 9, 4 ],
 *   [ 7, 6, 5 ]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 00:54
 */
public class _0059_SpiralMatrixII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Spiral Matrix II.
     *
     * Memory Usage: 34.3 MB, less than 8.33% of Java online submissions for Spiral Matrix II.
     */
    public int[][] generateMatrix(int n) {
        int x1 = 0, x2 = n - 1;
        int y1 = 0, y2 = n - 1;
        int i = 1;
        int[][] matrix = new int[n][n];
        while (x1 <= x2 && y1 <= y2) {
            for (int x = x1; x <= x2; x++) {
                matrix[y1][x] = i++;
            }
            for (int y = y1 + 1; y <= y2; y++) {
                matrix[y][x2] = i++;
            }
            if (x1 < x2 && y1 < y2) {
                for (int x = x2 - 1; x > x1; x--) {
                    matrix[y2][x] = i++;
                }
                for (int y = y2; y > y1; y--) {
                    matrix[y][x1] = i++;
                }
            }
            x1++;
            x2--;
            y1++;
            y2--;
        }

        return matrix;
    }

    public static void main(String[] args) {
        _0059_SpiralMatrixII solution = new _0059_SpiralMatrixII();
        int[][] r1 = solution.generateMatrix(5);
        printMatrix(r1);
    }
}

60. Permutation Sequence

The set [1,2,3,…​,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

  1. "123"

  2. "132"

  3. "213"

  4. "231"

  5. "312"

  6. "321"

Given n and k, return the kth permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.

  • Given k will be between 1 and n! inclusive.

Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"

解题分析

0060 5
0060 6

不需要生成所有的全排列。如图,通过剪枝,只需要生成需要的排列的路径即可。

这里的重点是如何剪枝!

思考题

对回溯再推敲推敲!

参考资料

The set [1,2,3,…​,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

  • "123"

  • "132"

  • "213"

  • "231"

  • "312"

  • "321"

Given n and k, return the kth permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.

  • Given k will be between 1 and n! inclusive.

Example 1:

Input: n = 3, k = 3
Output: "213"

Example 2:

Input: n = 4, k = 9
Output: "2314"
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 60. Permutation Sequence
 *
 * https://leetcode.com/problems/permutation-sequence/[Permutation Sequence - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-03 22:42
 */
public class _0060_PermutationSequence {

    /**
     * Runtime: 1 ms, faster than 99.26% of Java online submissions for Permutation Sequence.
     * Memory Usage: 37.2 MB, less than 20.83% of Java online submissions for Permutation Sequence.
     *
     * Copy from: https://leetcode-cn.com/problems/permutation-sequence/solution/hui-su-jian-zhi-python-dai-ma-java-dai-ma-by-liwei/[深度优先遍历 + 剪枝、双链表模拟 - 第k个排列 - 力扣(LeetCode)]
     */
    private boolean[] used;
    private int[] factorial;
    private int n;
    private int k;
    private List<Integer> path;
    public String getPermutation(int n, int k) {
        this.n = n;
        this.k = k;
        used = new boolean[n + 1];
        factorial = new int[n + 1];
        factorial[0] = 1;
        for (int i = 1; i <= n; i++) {
            factorial[i] = factorial[i - 1] * i;
        }
        path = new ArrayList<>();
        dfs(0);
        StringBuilder builder = new StringBuilder();
        for (Integer integer : path) {
            builder.append(integer);
        }
        return builder.toString();
    }

    private void dfs(int index) {
        if (index == n) {
            return;
        }
        int cnt = factorial[n - 1 - index];
        for (int i = 1; i <= n; i++) {
            if (used[i]) {
                continue;
            }
            if (cnt < k) {
                k -= cnt;
                continue;
            }
            path.add(i);
            used[i] = true;
            dfs(index + 1);
        }
    }

    /**
     * Time Limit Exceeded
     */
    public String getPermutationRecursion(int n, int k) {
        List<Integer> nums = new ArrayList<>(n);
        for (int i = 1; i <= n; i++) {
            nums.add(i);
        }
        List<String> permutations = new LinkedList<>();
        permutations(nums, 0, permutations);
        ArrayList<String> sp = new ArrayList<>(permutations);
        sp.sort(Comparator.naturalOrder());
        return sp.get(k - 1);
    }

    private void permutations(List<Integer> nums, int index, List<String> result) {
        if (index == nums.size()) {
            StringBuilder builder = new StringBuilder(index);
            for (int num : nums) {
                builder.append(num);
            }
            result.add(builder.toString());
            return;
        }
        for (int i = index; i < nums.size(); i++) {
            Collections.swap(nums, i, index);
            permutations(nums, index + 1, result);
            Collections.swap(nums, i, index);
        }
    }

    public static void main(String[] args) {
        _0060_PermutationSequence solution = new _0060_PermutationSequence();

        String r1 = solution.getPermutation(3, 3);
        System.out.println("213".equals(r1) + " : " + r1);

        String r2 = solution.getPermutation(4, 9);
        System.out.println("2314".equals(r2) + " : " + r2);
    }
}

61. Rotate List

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

解题分析

0061 1

这个环形解题法很赞!

参考资料

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 61. Rotate List
 *
 * https://leetcode.com/problems/rotate-list/[Rotate List - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-01 23:11
 */
public class _0061_RotateList {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate List.
     * Memory Usage: 38.8 MB, less than 46.55% of Java online submissions for Rotate List.
     *
     * Copy from: https://leetcode-cn.com/problems/rotate-list/solution/xuan-zhuan-lian-biao-by-leetcode/[旋转链表 - 旋转链表 - 力扣(LeetCode)]
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (Objects.isNull(head) || Objects.isNull(head.next) || k == 0) {
            return head;
        }

        ListNode current = head;
        int length;
        for (length = 1; Objects.nonNull(current.next); length++) {
            current = current.next;
        }

        int pass = length - k % length;
        if (pass == length || pass == 0) {
            return head;
        }
        current.next = head;

        current = head;
        for (int i = 0; i < pass - 1; i++) {
            current = current.next;
        }
        ListNode result = current.next;
        current.next = null;

        return result;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate List.
     * Memory Usage: 38.7 MB, less than 55.17% of Java online submissions for Rotate List.
     */
    public ListNode rotateRightLoop(ListNode head, int k) {
        if (Objects.isNull(head)) {
            return null;
        }
        if (k == 0) {
            return head;
        }
        ListNode current = head;
        int length = 0;
        while (Objects.nonNull(current)) {
            length++;
            current = current.next;
        }
        int pass = length - k % length;
        if (pass == length || pass == 0) {
            return head;
        }
        current = head;
        for (int i = 0; i < pass - 1; i++) {
            current = current.next;
        }
        ListNode result = current.next;
        current.next = null;
        current = result;
        while (Objects.nonNull(current)) {
            if (Objects.isNull(current.next)) {
                break;
            }
            current = current.next;
        }
        current.next = head;

        return result;
    }

    public static void main(String[] args) {
        _0061_RotateList solution = new _0061_RotateList();
        printListNode(solution.rotateRight(build(asList(1, 2, 3, 4, 5)), 2));
        printListNode(solution.rotateRight(build(asList(0, 1, 2)), 4));
    }
}

62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

robot maze

Above is a 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 62. Unique Paths
 *
 * https://leetcode.com/problems/unique-paths/[Unique Paths - LeetCode]
 *
 * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
 *
 * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
 *
 * How many possible unique paths are there?
 *
 * *Note:* m and n will be at most 100.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: m = 3, n = 2
 * Output: 3
 * Explanation:
 * From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
 * 1. Right -> Right -> Down
 * 2. Right -> Down -> Right
 * 3. Down -> Right -> Right
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: m = 7, n = 3
 * Output: 28
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 22:56
 */
public class _0062_UniquePaths {
    public int uniquePaths(int m, int n) {
        if (m == 0 || n == 0) {
            return 0;
        }
        int[] row = new int[n];
        Arrays.fill(row, 1);
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                row[j] = row[j - 1] + row[j];
            }
        }
        return row[n - 1];
    }

    /**
     * timeout
     */
    public int uniquePathsBottomUp(int m, int n) {
        if (m == 0 || n == 0) {
            return 0;
        }
        if (m == 1 || n == 1) {
            return 1;
        }
        return uniquePathsBottomUp(m - 1, n) + uniquePathsBottomUp(m, n - 1);
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths.
     * <p>
     * Memory Usage: 33 MB, less than 5.10% of Java online submissions for Unique Paths.
     */
    public int uniquePathsMatrix(int m, int n) {
        if (m == 0 || n == 0) {
            return 0;
        }
        int[][] paths = new int[m][n];
        for (int i = 0; i < m; i++) {
            paths[i][0] = 1;
        }
        for (int i = 1; i < n; i++) {
            paths[0][i] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                paths[i][j] = paths[i - 1][j] + paths[i][j - 1];
            }
        }
        return paths[m - 1][n - 1];
    }

    public static void main(String[] args) {
        _0062_UniquePaths solution = new _0062_UniquePaths();
        int r1 = solution.uniquePaths(3, 2);
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.uniquePaths(7, 3);
        System.out.println((r2 == 28) + " : " + r2);

        int r3m = solution.uniquePathsMatrix(23, 12);
        System.out.println((r3m == 193536720) + " : " + r3m);

        int r3 = solution.uniquePaths(23, 12);
        System.out.println((r3 == 193536720) + " : " + r3);

        int r4m = solution.uniquePathsMatrix(100, 81);
        System.out.println((r4m == 1780241190) + " : " + r4m);

        int r4 = solution.uniquePaths(100, 81);
        System.out.println((r4 == 1780241190) + " : " + r4);
    }
}

63. Unique Paths II

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

robot maze

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

Example 1:

Input:
*[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
*Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 63. Unique Paths II
 *
 * https://leetcode.com/problems/unique-paths-ii/[Unique Paths II - LeetCode]
 *
 * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
 *
 * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
 *
 * Now consider if some obstacles are added to the grids. How many unique paths would there be?
 *
 * An obstacle and empty space is marked as 1 and 0 respectively in the grid.
 *
 * *Note:* m and n will be at most 100.
 *
 * .Example 1:
 * [source]
 * ----
 * Input:
 * [
 *   [0,0,0],
 *   [0,1,0],
 *   [0,0,0]
 * ]
 * Output: 2
 * Explanation:
 * There is one obstacle in the middle of the 3x3 grid above.
 * There are two ways to reach the bottom-right corner:
 * 1. Right -> Right -> Down -> Down
 * 2. Down -> Down -> Right -> Right
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 23:50
 */
public class _0063_UniquePathsII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths II.
     * <p>
     * Memory Usage: 40.5 MB, less than 33.84% of Java online submissions for Unique Paths II.
     */
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (Objects.isNull(obstacleGrid)
                || obstacleGrid.length == 0
                || obstacleGrid[0].length == 0
                || obstacleGrid[0][0] == 1) {
            return 0;
        }
        obstacleGrid[0][0] = 1;

        int m = obstacleGrid.length;
        for (int i = 1; i < m; i++) {
            if (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) {
                obstacleGrid[i][0] = 1;
            } else {
                obstacleGrid[i][0] = 0;
            }
        }
        int n = obstacleGrid[0].length;
        for (int j = 1; j < n; j++) {
            if (obstacleGrid[0][j] == 0 && obstacleGrid[0][j - 1] == 1) {
                obstacleGrid[0][j] = 1;
            } else {
                obstacleGrid[0][j] = 0;
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    obstacleGrid[i][j] = 0;
                } else {
                    obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
                }
            }
        }
        return obstacleGrid[m - 1][n - 1];
    }

    /**
     * Runtime: 1 ms, faster than 23.04% of Java online submissions for Unique Paths II.
     * <p>
     * Memory Usage: 40.5 MB, less than 35.38% of Java online submissions for Unique Paths II.
     */
    public int uniquePathsWithObstaclesMy(int[][] obstacleGrid) {
        if (Objects.isNull(obstacleGrid)
                || obstacleGrid.length == 0
                || obstacleGrid[0].length == 0) {
            return 0;
        }
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        boolean hasObstacle = false;
        for (int i = 0; i < n; i++) {
            int value = obstacleGrid[0][i];
            if (value == 1) {
                hasObstacle = true;
                obstacleGrid[0][i] = -1;
            } else {
                if (hasObstacle) {
                    obstacleGrid[0][i] = 0;
                } else {
                    obstacleGrid[0][i] = 1;
                }
            }
        }
        hasObstacle = false;
        if (obstacleGrid[0][0] == -1) {
            hasObstacle = true;
        }
        for (int i = 1; i < m; i++) {
            int value = obstacleGrid[i][0];
            if (hasObstacle) {
                obstacleGrid[i][0] = 0;
            }
            if (value == 1) {
                hasObstacle = true;
                obstacleGrid[i][0] = -1;
            } else {
                if (hasObstacle) {
                    obstacleGrid[i][0] = 0;
                } else {
                    obstacleGrid[i][0] = 1;
                }
            }
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                int value = obstacleGrid[i][j];
                if (value == 1) {
                    obstacleGrid[i][j] = -1;
                } else {
                    int top = obstacleGrid[i - 1][j];
                    if (top == -1) {
                        top = 0;
                    }

                    int left = obstacleGrid[i][j - 1];
                    if (left == -1) {
                        left = 0;
                    }
                    obstacleGrid[i][j] = top + left;
                }
            }
        }
        return Math.max(obstacleGrid[m - 1][n - 1], 0);
    }

    public static void main(String[] args) {
        _0063_UniquePathsII solution = new _0063_UniquePathsII();
        int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
        int r1 = solution.uniquePathsWithObstacles(obstacleGrid);
        System.out.println((r1 == 2) + " : " + r1);

        int[][] obstacleGrid2 = {{1}};
        int r2 = solution.uniquePathsWithObstacles(obstacleGrid2);
        System.out.println((r2 == 0) + " : " + r2);

        int[][] obstacleGrid3 = {{1, 1}};
        int r3 = solution.uniquePathsWithObstacles(obstacleGrid3);
        System.out.println((r3 == 0) + " : " + r3);

        int[][] obstacleGrid4 = {{1, 0}};
        int r4 = solution.uniquePathsWithObstacles(obstacleGrid4);
        System.out.println((r4 == 0) + " : " + r4);

        int[][] obstacleGrid5 = {{1}, {0}};
        int r5 = solution.uniquePathsWithObstacles(obstacleGrid5);
        System.out.println((r5 == 0) + " : " + r5);
    }
}

64. Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:
Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
0064 1
0064 2

思考题:尝试使用一维数组做备忘录来实现一下。

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1&rarr;3&rarr;1&rarr;1&rarr;1 minimizes the sum.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 64. Minimum Path Sum
 *
 * https://leetcode.com/problems/minimum-path-sum/[Minimum Path Sum - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 21:29
 */
public class _0064_MinimumPathSum {
    /**
     * Runtime: 7 ms, faster than 5.53% of Java online submissions for Minimum Path Sum.
     * Memory Usage: 43.5 MB, less than 33.78% of Java online submissions for Minimum Path Sum.
     */
    public int minPathSum(int[][] grid) {
        if (Objects.isNull(grid) || grid.length == 0) {
            return 0;
        }
        int yLength = grid.length;
        int xLength = grid[0].length;

        for (int y = 0; y < yLength; y++) {
            for (int x = 0; x < xLength; x++) {
                if (y == 0 && x > 0) {
                    grid[y][x] = grid[y][x - 1] + grid[y][x];
                } else if (y > 0 && x == 0) {
                    grid[y][x] = grid[y - 1][x] + grid[y][x];
                } else if (y > 0 && x > 0) {
                    grid[y][x] = Math.min(grid[y - 1][x], grid[y][x - 1]) + grid[y][x];
                }
            }
        }

        return grid[yLength - 1][xLength - 1];
    }

    /**
     * Runtime: 5 ms, faster than 7.69% of Java online submissions for Minimum Path Sum.
     * Memory Usage: 43.2 MB, less than 36.48% of Java online submissions for Minimum Path Sum.
     */
    public int minPathSumDp(int[][] grid) {
        if (Objects.isNull(grid) || grid.length == 0) {
            return 0;
        }
        int yLength = grid.length;
        int xLength = grid[0].length;

        int[][] sums = new int[yLength][xLength];

        for (int i = 1; i < sums.length; i++) {
            Arrays.fill(sums[i], Integer.MAX_VALUE);
        }

        sums[0][0] = grid[0][0];
        for (int x = 1; x < xLength; x++) {
            sums[0][x] = sums[0][x - 1] + grid[0][x];
        }
        for (int y = 1; y < yLength; y++) {
            sums[y][0] = sums[y - 1][0] + grid[y][0];
        }
        for (int y = 1; y < yLength; y++) {
            for (int x = 1; x < xLength; x++) {
                sums[y][x] = Math.min(sums[y - 1][x], sums[y][x - 1]) + grid[y][x];
            }
        }
        return sums[yLength - 1][xLength - 1];
    }

    public static void main(String[] args) {
        _0064_MinimumPathSum solution = new _0064_MinimumPathSum();
        int[][] g1 = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        int r1 = solution.minPathSum(g1);
        System.out.println((r1 == 7) + " : " + r1);

        int[][] g2 = {{1, 2}, {5, 6}, {1, 1}};
        int r2 = solution.minPathSum(g2);
        System.out.println((r2 == 8) + " : " + r2);
    }
}

65. Valid Number

Validate if a given string can be interpreted as a decimal number.

Some examples:

"0"true

" 0.1 "true

"abc"false

"1 a"false

"2e10"true

" -90e3 "true

" 1e"false

"e3"false

" 6e-1"true

" 99e2.5 "false

"53.5e93"true

" --6 "false

"-+3"false

"95a54e53"false

Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:

  • Numbers 0-9

  • Exponent - "e"

  • Positive/negative sign - "+"/"-"

  • Decimal point - "."

Of course, the context of these characters also matters in the input.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package com.diguage.algorithm.leetcode;

/**
 * = 65. Valid Number
 *
 * https://leetcode.com/problems/valid-number/[Valid Number - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-26 18:59
 */
public class _0065_ValidNumber {
    // TODO Hard
}

66. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 66. Plus One
 *
 * https://leetcode.com/problems/plus-one/description/[Plus One - LeetCode]
 *
 * Given a *non-empty* array of digits representing a non-negative integer,
 * plus one to the integer.
 *
 * The digits are stored such that the most significant digit is at the
 * head of the list, and each element in the array contain a single digit.
 *
 * You may assume the integer does not contain any leading zero, except
 * the number 0 itself.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,2,3]
 * Output: [1,2,4]
 * Explanation: The array represents the integer 123.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [4,3,2,1]
 * Output: [4,3,2,2]
 * Explanation: The array represents the integer 4321.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2018-07-14 15:30
 */
public class _0066_PlusOne {
    public static int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0) {
            return digits;
        }
        for (int i = digits.length - 1; i >= 0; i--) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            } else {
                digits[i] = 0;
            }
        }

        int[] result = new int[digits.length + 1];
        result[0] = 1;
        return result;
    }

    public static void main(String[] args) {
        int[] a1 = new int[]{4, 3, 2, 1};
        int[] a2 = new int[]{9, 9, 9};
        int[] a3 = new int[]{9, 9, 8};
        System.out.println(Arrays.toString(plusOne(a1)));
        System.out.println(Arrays.toString(plusOne(a2)));
        System.out.println(Arrays.toString(plusOne(a3)));
    }
}

67. Add Binary

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.diguage.algorithm.leetcode;

/**
 * = 67. Add Binary
 *
 * https://leetcode.com/problems/add-binary/[Add Binary - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-02 22:27
 */
public class _0067_AddBinary {
    /**
     * Runtime: 2 ms, faster than 64.49% of Java online submissions for Add Binary.
     * Memory Usage: 38.3 MB, less than 5.62% of Java online submissions for Add Binary.
     */
    public String addBinary(String a, String b) {
        StringBuilder result = new StringBuilder();
        int carr = 0;
        for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {
            int ai = i >= 0 ? a.charAt(i) - '0' : 0;
            int bi = j >= 0 ? b.charAt(j) - '0' : 0;
            int sum = carr + ai + bi;
            result.append(sum & 1);
            carr = (sum >>> 1) & 1;
        }
        result.append(carr > 0 ? carr : "");
        return result.reverse().toString();
    }

    public static void main(String[] args) {
        _0067_AddBinary sollution = new _0067_AddBinary();
        String r1 = sollution.addBinary("11", "1");
        System.out.println("100".equals(r1) + " : " + r1);

        String r2 = sollution.addBinary("1010", "1011");
        System.out.println("10101".equals(r2) + " : " + r2);
    }
}

68. Text Justification

Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

Note:

  • A word is defined as a character sequence consisting of non-space characters only.

  • Each word’s length is guaranteed to be greater than 0 and not exceed maxWidth.

  • The input array words contains at least one word.

Example 1:

Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Example 2:

Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be",
             because the last line must be left-justified instead of fully-justified.
             Note that the second line is also left-justified becase it contains only one word.

Example 3:

Input:
words = ["Science","is","what","we","understand","well","enough","to","explain",
         "to","a","computer.","Art","is","everything","else","we","do"]
maxWidth = 20
Output:
[
  "Science  is  what we",
  "understand      well",
  "enough to explain to",
  "a  computer.  Art is",
  "everything  else  we",
  "do                  "
]
1
Unresolved directive in 0068-text-justification.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0068_TextJustification.java[]

69. Sqrt(x)

明知使用的是二分查找,竟然没有写出来!!

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
             the decimal part is truncated, 2 is returned.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.diguage.algorithm.leetcode;

/**
 * = 69. Sqrt(x)
 *
 * https://leetcode.com/problems/sqrtx/[Sqrt(x) - LeetCode]
 *
 * Implement int `sqrt(int x)`.
 *
 * Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
 *
 * Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 4
 * Output: 2
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 8
 * Output: 2
 * Explanation: The square root of 8 is 2.82842..., and since
 *              the decimal part is truncated, 2 is returned.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-13 22:30
 */
public class _0069_SqrtX {
    /**
     * Runtime: 2 ms, faster than 14.88% of Java online submissions for Sqrt(x).
     *
     * Memory Usage: 34.1 MB, less than 5.00% of Java online submissions for Sqrt(x).
     *
     * Copy from: https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution[A Binary Search Solution - LeetCode Discuss]
     */
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        int left = 1;
        int right = x;
        while (true) {
            int mid = left + (right - left) / 2;

            if (mid > x / mid) {
                right = mid - 1;
            } else {
                if (mid + 1 > x / (mid + 1)) {
                    return mid;
                }
                left = mid + 1;
            }
        }
    }

    public static void main(String[] args) {
        _0069_SqrtX solution = new _0069_SqrtX();

        int r5 = solution.mySqrt(9);
        System.out.println((r5 == 3) + " : " + r5);

        int r4 = solution.mySqrt(1024);
        System.out.println((r4 == 32) + " : " + r4);

        int r1 = solution.mySqrt(2);
        System.out.println((r1 == 1) + " : " + r1);

        int r2 = solution.mySqrt(8);
        System.out.println((r2 == 2) + " : " + r2);

        int r3 = solution.mySqrt(1);
        System.out.println((r3 == 1) + " : " + r3);
    }
}

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

解题分析

最简单只有一个台阶,只有 1 种方法;

当有两个台阶时,可以从地面跳起;也可以从第一个台阶跳起;

以此类推:当第 n 个台阶时,可以从第 n-2 个台阶跳起;也可以从第 n-1 个台阶跳起。

0070 1

到这里就很明显了,这是一个斐波那契数列。

让 D瓜哥 使用 动态规划的模式 来重新解读一下:

  1. 刻画一个最优解的结构特征:跳到第 n 个台阶最多的跳法。

  2. 递归地定义最优解的值: dp[n] = dp[n-2] + dp[n-1]

  3. 计算最优解的值,通常采用自底向上的方法:D瓜哥也按照动态规划(注意表格)的方式来实现,采用自底向上+备忘录的方式来求解,创建一个长度为 n+1 的数组,第 i 个元素表示有相应的跳法,则第 1 个元素为 1,第 2 个元素为 2。然后以此类推……

  4. 利用计算出的信息构造一个最优解。这一步不需要,暂时忽略。

D瓜哥 再插播一句,知道是斐波那契数列,各种解法都好搞了,甚至可以使用斐波那契数列公式来解题了。😆

\$F_{n}=1 / \sqrt{5}\left[\left(\frac{1+\sqrt{5}}{2}\right)^{n}-\left(\frac{1-\sqrt{5}}{2}\right)^{n}\right]\$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.diguage.algorithm.leetcode;

/**
 * = 70. Climbing Stairs
 *
 * https://leetcode.com/problems/climbing-stairs/[Climbing Stairs - LeetCode]
 *
 * You are climbing a stair case. It takes n steps to reach to the top.
 *
 * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
 *
 * *Note:* Given n will be a positive integer.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 2
 * Output: 2
 * Explanation: There are two ways to climb to the top.
 * 1. 1 step + 1 step
 * 2. 2 steps
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 3
 * Output: 3
 * Explanation: There are three ways to climb to the top.
 * 1. 1 step + 1 step + 1 step
 * 2. 1 step + 2 steps
 * 3. 2 steps + 1 step
 * ----
 *
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-23 21:29
 */
public class _0070_ClimbingStairs {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
     *
     * Memory Usage: 40.8 MB, less than 5.26% of Java online submissions for Climbing Stairs.
     *
     * Copy from: https://leetcode.com/problems/climbing-stairs/solution/[Climbing Stairs solution - LeetCode]
     */
    public int climbStairs(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    public static void main(String[] args) {
        _0070_ClimbingStairs solution = new _0070_ClimbingStairs();
        int r1 = solution.climbStairs(2);
        System.out.println((r1 == 2) + " : " + r1);

        int r2 = solution.climbStairs(3);
        System.out.println((r2 == 3) + " : " + r2);

        int r3 = solution.climbStairs(4);
        System.out.println((r3 == 5) + " : " + r3);
    }
}

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix.

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"

解题分析

有点想复杂了,只需要一个字符串分割,然后加一个辅助栈即可。

不过,我感觉滑动窗口应该也可以,回头可以试试。

参考资料

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

Input: "/a//b////c/d//././/.."
Output: "/a/b/c"
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.diguage.algorithm.leetcode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;

/**
 * = 71. Simplify Path
 *
 * https://leetcode.com/problems/simplify-path/[Simplify Path - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 16:15
 */
public class _0071_SimplifyPath {
    /**
     * Runtime: 5 ms, faster than 71.14% of Java online submissions for Simplify Path.
     * Memory Usage: 39.9 MB, less than 6.67% of Java online submissions for Simplify Path.
     */
    public String simplifyPath(String path) {
        String[] paths = path.split("/");
        Deque<String> stack = new LinkedList<>();
        for (String subpath : paths) {
            if ("..".equals(subpath) && !stack.isEmpty()) {
                stack.removeLast();
                continue;
            }
            if (subpath.length() > 0 && !".".equals(subpath) && !"..".equals(subpath)) {
                stack.addLast(subpath);
            }
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            String name = stack.removeFirst();
            result.append("/").append(name);
        }
        return result.length() > 0 ? result.toString() : "/";
    }

    /**
     * Runtime: 3 ms, faster than 97.40% of Java online submissions for Simplify Path.
     * Memory Usage: 39.4 MB, less than 20.00% of Java online submissions for Simplify Path.
     */
    public String simplifyPathLoop(String path) {
        if (Objects.isNull(path)) {
            return "/";
        }
        Deque<String> stack = new LinkedList<>();
        int i = 0;
        while (i < path.length()) {
            if (path.charAt(i) == '/') {
                i++;
                continue;
            }
            StringBuilder sb = new StringBuilder();
            while (i < path.length() && (path.charAt(i) != '.' && path.charAt(i) != '/')) {
                sb.append(path.charAt(i));
                i++;
            }

            if (sb.length() > 0) {
                stack.addLast(sb.toString());
                continue;
            }
            while (i < path.length() && path.charAt(i) != '/') {
                sb.append(path.charAt(i));
                i++;
            }
            String strings = sb.toString();
            if (sb.length() == 2 && !stack.isEmpty() && "..".equals(strings)) {
                stack.removeLast();
            }
            if (sb.length() > 2 || (sb.length() == 2 && !"..".equals(strings))) {
                stack.addLast(strings);
            }
        }
        if (stack.isEmpty()) {
            return "/";
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) {
            String name = stack.removeFirst();
            result.append("/").append(name);
        }
        return result.length() > 0 ? result.toString() : "/";
    }

    public static void main(String[] args) {
        _0071_SimplifyPath solution = new _0071_SimplifyPath();

        String r9 = solution.simplifyPath("/home/foo/.ssh/../.ssh2/authorized_keys/");
        System.out.println("/home/foo/.ssh2/authorized_keys".equals(r9) + " : " + r9);

        String r8 = solution.simplifyPath("/home/foo/.ssh/authorized_keys/");
        System.out.println("/home/foo/.ssh/authorized_keys".equals(r8) + " : " + r8);

        String r7 = solution.simplifyPath("/..hidden");
        System.out.println("/..hidden".equals(r7) + " : " + r7);

        String r1 = solution.simplifyPath("/home/");
        System.out.println("/home".equals(r1) + " : " + r1);

        String r2 = solution.simplifyPath("/../");
        System.out.println("/".equals(r2) + " : " + r2);

        String r3 = solution.simplifyPath("/home//foo/");
        System.out.println("/home/foo".equals(r3) + " : " + r3);

        String r4 = solution.simplifyPath("/a/./b/../../c/");
        System.out.println("/c".equals(r4) + " : " + r4);

        String r5 = solution.simplifyPath("/a/../../b/../c//.//");
        System.out.println("/c".equals(r5) + " : " + r5);

        String r6 = solution.simplifyPath("/a//b////c/d//././/..");
        System.out.println("/a/b/c".equals(r6) + " : " + r6);
    }
}

72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character

  2. Delete a character

  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
1
Unresolved directive in 0072-edit-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0072_EditDistance.java[]

73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input:
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output:
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input:
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output:
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

Follow up:

  • A straight forward solution using O(m__n) space is probably a bad idea.

  • A simple improvement uses O(m + n) space, but still not the best solution.

  • Could you devise a constant space solution?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 73. Set Matrix Zeroes
 *
 * https://leetcode.com/problems/set-matrix-zeroes/[Set Matrix Zeroes - LeetCode]
 *
 * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
 *
 * .Example 1:
 * [source]
 * ----
 * Input:
 * [
 *   [1,1,1],
 *   [1,0,1],
 *   [1,1,1]
 * ]
 * Output:
 * [
 *   [1,0,1],
 *   [0,0,0],
 *   [1,0,1]
 * ]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * [
 *   [0,1,2,0],
 *   [3,4,5,2],
 *   [1,3,1,5]
 * ]
 * Output:
 * [
 *   [0,0,0,0],
 *   [0,4,5,0],
 *   [0,3,1,0]
 * ]
 * ----
 *
 * *Follow up:*
 *
 * * A straight forward solution using O(mn) space is probably a bad idea.
 * * A simple improvement uses O(m + n) space, but still not the best solution.
 * * Could you devise a constant space solution?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-27 00:59
 */
public class _0073_SetMatrixZeroes {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Set Matrix Zeroes.
     *
     * Memory Usage: 50.4 MB, less than 5.71% of Java online submissions for Set Matrix Zeroes.
     */
    public void setZeroes(int[][] matrix) {
        if (Objects.isNull(matrix) || matrix[0].length == 0) {
            return;
        }
        /**
         * 0 all is 0;
         * 1 row is 0;
         * 2 column is 0;
         * 3 is not 0;
         */
        int flag = 3;
        int value = matrix[0][0];
        if (value == 0) {
            flag = 0;
        }
        int column = matrix.length;
        int row = matrix[0].length;
        for (int i = 0; i < column; i++) {
            for (int j = 0; j < row; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                    if (i == 0 && j > 0 && flag != 0) {
                        flag = 1;
                    }
                    if (i > 0 && j == 0 && flag != 0) {
                        if (flag == 1) {
                            flag = 0;
                        } else {
                            flag = 2;
                        }
                    }
                }
            }
        }
//        printMatrix(matrix);
        for (int i = 1; i < column; i++) {
            if (matrix[i][0] == 0) {
                Arrays.fill(matrix[i], 0);
            }
        }
        for (int j = 1; j < row; j++) {
            if (matrix[0][j] == 0) {
                for (int i = 0; i < column; i++) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (flag == 0) {
            Arrays.fill(matrix[0], 0);
            for (int i = 0; i < column; i++) {
                matrix[i][0] = 0;
            }
        } else if (flag == 1) {
            Arrays.fill(matrix[0], 0);
        } else if (flag == 2) {
            for (int i = 0; i < column; i++) {
                matrix[i][0] = 0;
            }
        }
    }

    public static void main(String[] args) {
        _0073_SetMatrixZeroes solution = new _0073_SetMatrixZeroes();
//        int[][] matrix = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
//        printMatrix(matrix);
//        solution.setZeroes(matrix);
//        printMatrix(matrix);
//
//        int[][] matrix2 = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 0, 1, 5}};
//        printMatrix(matrix2);
//        solution.setZeroes(matrix2);
//        printMatrix(matrix2);
//
//        int[][] matrix3 = {{6, 1, 2, 7}, {0, 4, 5, 2}, {1, 3, 1, 5}};
//        printMatrix(matrix3);
//        solution.setZeroes(matrix3);
//        printMatrix(matrix3);
//
//        int[][] matrix4 = {{6, 1, 0, 7}, {8, 4, 5, 2}, {1, 3, 1, 5}};
//        printMatrix(matrix4);
//        solution.setZeroes(matrix4);
//        printMatrix(matrix4);

        int[][] matrix5 = {
                {8, 3, 6, 9, 7, 8, 0, 6},
                {0, 3, 7, 0, 0, 4, 3, 8},
                {5, 3, 6, 7, 1, 6, 2, 6},
                {8, 7, 2, 5, 0, 6, 4, 0},
                {0, 2, 9, 9, 3, 9, 7, 3}};
        printMatrix(matrix5);
        solution.setZeroes(matrix5);
        printMatrix(matrix5);
    }
}

74. Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.

  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false
1
Unresolved directive in 0074-search-a-2d-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0074_SearchA2DMatrix.java[]

75. Sort Colors

Given an array with n objects colored red, white or blue, sort them *https://en.wikipedia.org/wiki/In-place_algorithm[in-place] *so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library’s sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort.

    	First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
    * Could you come up with a one-pass algorithm using only constant space?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 75. Sort Colors
 *
 * https://leetcode.com/problems/sort-colors/[Sort Colors - LeetCode]
 *
 * Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
 *
 * Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
 *
 * Note: You are not suppose to use the library's sort function for this problem.
 *
 * .Example:
 * [source]
 * ----
 * Input: [2,0,2,1,1,0]
 * Output: [0,0,1,1,2,2]
 * ----
 *
 * *Follow up:*
 *
 * * A rather straight forward solution is a two-pass algorithm using counting sort.
 * +
 * First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
 * +
 * * Could you come up with a one-pass algorithm using only constant space?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-29 01:01
 */
public class _0075_SortColors {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Sort Colors.
     *
     * Memory Usage: 35.2 MB, less than 99.21% of Java online submissions for Sort Colors.
     */
    public void sortColors(int[] nums) {
        if (Objects.isNull(nums) || nums.length <= 1) {
            return;
        }
        int current = 0;
        int head = 0;
        int tail = nums.length - 1;
        while (current <= tail) {
            if (nums[current] == 0) {
                swap(nums, current, head);
                head++;
                current++;
            } else if (nums[current] == 2) {
                swap(nums, current, tail);
                tail--;
                // 这了不需要 current++,就是把这个数字重新排队一遍!
            } else {
                current++;
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        _0075_SortColors solution = new _0075_SortColors();
        int[] array = {2, 0, 2, 1, 1, 0};
        System.out.println(Arrays.toString(array));
        solution.sortColors(array);
        System.out.println(Arrays.toString(array));

        int[] array2 = {1, 2, 0, 0};
        System.out.println(Arrays.toString(array2));
        solution.sortColors(array2);
        System.out.println(Arrays.toString(array2));

        int[] array3 = {1, 2, 2, 2, 2, 0, 0, 0, 1, 1};
        System.out.println(Arrays.toString(array3));
        solution.sortColors(array3);
        System.out.println(Arrays.toString(array3));
    }
}

76. Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".

  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

参考资料

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".

  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 76. Minimum Window Substring
 *
 * https://leetcode.com/problems/minimum-window-substring/[Minimum Window Substring - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 16:15
 */
public class _0076_MinimumWindowSubstring {

    /**
     * Runtime: 489 ms, faster than 5.03% of Java online submissions for Minimum Window Substring.
     * Memory Usage: 322.8 MB, less than 5.32% of Java online submissions for Minimum Window Substring.
     *
     * ↓ 优化:在最后输出时,才截取字符串。
     *
     * Runtime: 33 ms, faster than 16.02% of Java online submissions for Minimum Window Substring.
     * Memory Usage: 44.4 MB, less than 5.32% of Java online submissions for Minimum Window Substring.
     */
    public String minWindow(String s, String t) {
        if (Objects.isNull(s) || s.length() == 0
                || Objects.isNull(t) || t.length() == 0
                || s.length() < t.length()) {
            return "";
        }
        Map<Character, Integer> needs = new HashMap<>(t.length());
        for (char c : t.toCharArray()) {
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        int minLength = Integer.MAX_VALUE;
        int start = 0;
        int match = 0;
        Map<Character, Integer> windows = new HashMap<>(t.length());
        while (right < s.length()) {
            char rChar = s.charAt(right);
            if (needs.containsKey(rChar)) {
                int rCount = windows.getOrDefault(rChar, 0) + 1;
                windows.put(rChar, rCount);
                if (rCount == needs.get(rChar)) {
                    match++;
                }
            }
            right++;

            while (match == needs.size()) {
                if (right - left < minLength) {
                    minLength = right - left;
                    start = left;
                }
                char lChar = s.charAt(left);
                if (needs.containsKey(lChar)) {
                    int lCount = windows.get(lChar) - 1;
                    windows.put(lChar, lCount);
                    if (lCount < needs.get(lChar)) {
                        match--;
                    }
                }
                left++;
            }

        }
        return minLength == Integer.MAX_VALUE ? "" : s.substring(start, start + minLength);
    }

    public static void main(String[] args) {
        _0076_MinimumWindowSubstring solution = new _0076_MinimumWindowSubstring();
        String r1 = solution.minWindow("ADOBECODEBANC", "ABC");
        System.out.println("BANC".equals(r1) + " : " + r1);
    }
}

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 …​ n.

Example:
Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

解题分析

要注意和 46. Permutations 的区别。

思考题

尝试一下字典序组合解法。

参考资料

Given two integers n and k, return all possible combinations of k numbers out of 1 …​ n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 77. Combinations
 *
 * https://leetcode.com/problems/combinations/[Combinations - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 17:43
 */
public class _0077_Combinations {
    /**
     * Runtime: 20 ms, faster than 58.94% of Java online submissions for Combinations.
     * Memory Usage: 42.7 MB, less than 6.52% of Java online submissions for Combinations.
     */
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new LinkedList<>();
        dfs(n, k, 1, result, new LinkedList<>());
        return result;
    }

    private void dfs(int n, int k, int first, List<List<Integer>> result, Deque<Integer> current) {
        if (current.size() == k) {
            result.add(new ArrayList<>(current));
            return;
        }
        for (int i = first; i <= n; i++) {
            current.addLast(i);
            dfs(n, k, i + 1, result, current);
            current.removeLast();
        }
    }

    public static void main(String[] args) {
        _0077_Combinations solution = new _0077_Combinations();
        System.out.println(Arrays.toString(solution.combine(4, 2).toArray()));
    }
}

78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解题分析

这道题跟 90. Subsets II 类似。

0078 subsets recursion
0078 subsets combinations
0078 subsets backtracking
0078 subsets bitmask4

参考资料

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.diguage.algorithm.leetcode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * = 78. Subsets
 *
 * https://leetcode.com/problems/subsets/[Subsets - LeetCode]
 *
 * Given a set of *distinct* integers, nums, return all possible subsets (the power set).
 *
 * *Note:* The solution set must not contain duplicate subsets.
 *
 * .Example:
 * [source]
 * ----
 * Input: nums = [1,2,3]
 * Output:
 * [
 *   [3],
 *   [1],
 *   [2],
 *   [1,2,3],
 *   [1,3],
 *   [2,3],
 *   [1,2],
 *   []
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-02 19:56
 */
public class _0078_Subsets {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Subsets.
     *
     * Memory Usage: 37.1 MB, less than 99.18% of Java online submissions for Subsets.
     */
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<>());
        for (int num : nums) {
            List<List<Integer>> newSubsets = new ArrayList<>();
            for (List<Integer> current : result) {
                ArrayList<Integer> integers = new ArrayList<>(current);
                integers.add(num);
                newSubsets.add(integers);
            }
            result.addAll(newSubsets);
        }
        return result;
    }

    /**
     * Runtime: 74 ms, faster than 5.06% of Java online submissions for Subsets.
     *
     * Memory Usage: 50.3 MB, less than 5.74% of Java online submissions for Subsets.
     */
    public List<List<Integer>> subsetsLevel(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return Collections.emptyList();
        }
        Set<Set<Integer>> subsets = new HashSet<>();
        subsets.add(Collections.emptySet());
        for (int i = 0; i < nums.length; i++) {
            ArrayList<Set<Integer>> list = new ArrayList<>(subsets);
            list.forEach(s -> {
                for (int num : nums) {
                    Set<Integer> set = new TreeSet<>(s);
                    set.add(num);
                    subsets.add(set);
                }
            });
        }
        List<List<Integer>> result = subsets.stream()
                .map(ArrayList::new)
                .collect(Collectors.toList());
        return result;
    }

    public static void main(String[] args) {
        _0078_Subsets solution = new _0078_Subsets();
        int[] a1 = {1, 2, 3};
        List<List<Integer>> r1 = solution.subsets(a1);
        System.out.println(r1);
    }
}

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 79. Word Search
 *
 * https://leetcode.com/problems/word-search/[Word Search - LeetCode]
 *
 * Given a 2D board and a word, find if the word exists in the grid.
 *
 * The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
 *
 * .Example:
 * [source]
 * ----
 * board =
 * [
 *   ['A','B','C','E'],
 *   ['S','F','C','S'],
 *   ['A','D','E','E']
 * ]
 *
 * Given word = "ABCCED", return true.
 * Given word = "SEE", return true.
 * Given word = "ABCB", return false.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-03 17:31
 */
public class _0079_WordSearch {

    /**
     * Runtime: 4 ms, faster than 89.90% of Java online submissions for Word Search.
     *
     * Memory Usage: 38.4 MB, less than 97.96% of Java online submissions for Word Search.
     *
     * Copy from: https://leetcode.com/problems/word-search/discuss/27658/Accepted-very-short-Java-solution.-No-additional-space.[Accepted very short Java solution. No additional space. - LeetCode Discuss]
     */
    public boolean exist(char[][] board, String word) {
        if (Objects.isNull(board) || board.length == 0) {
            return false;
        }
        if (Objects.isNull(word) || word.length() == 0) {
            return false;
        }
        char[] chars = word.toCharArray();
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[y].length; x++) {
                if (exist(board, y, x, chars, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean exist(char[][] board, int y, int x, char[] word, int i) {
        if (i == word.length) {
            return true;
        }
        if (y < 0 || x < 0 || y == board.length || x == board[y].length) {
            return false;
        }
        if (board[y][x] != word[i]) {
            return false;
        }
        board[y][x] = Character.MAX_VALUE;
        boolean existable = exist(board, y - 1, x, word, i + 1)
                || exist(board, y, x + 1, word, i + 1)
                || exist(board, y + 1, x, word, i + 1)
                || exist(board, y, x - 1, word, i + 1);
        board[y][x] = word[i];
        return existable;
    }

    public static void main(String[] args) {
        _0079_WordSearch solution = new _0079_WordSearch();
        char[][] board = {
                {'A', 'B', 'C', 'E'},
                {'S', 'F', 'C', 'S'},
                {'A', 'D', 'E', 'E'}};
        String w1 = "ABCCED";
        boolean r1 = solution.exist(board, w1);
        System.out.println((r1) + " : " + r1);

        String w2 = "SEE";
        boolean r2 = solution.exist(board, w2);
        System.out.println((r2) + " : " + r2);

        String w3 = "ABCB";
        boolean r3 = solution.exist(board, w3);
        System.out.println((!r3) + " : " + r3);
    }
}

80. Remove Duplicates from Sorted Array II

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:
Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

解题分析

解题思路很简单:把后面的值覆盖前面多余的值。关键是如何用简单的代码来实现这个思路。

参考资料

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of `nums` being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of `nums` being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.diguage.algorithm.leetcode;

/**
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 20:57
 */
public class _0080_RemoveDuplicatesFromSortedArrayII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted Array II.
     * Memory Usage: 41.7 MB, less than 5.26% of Java online submissions for Remove Duplicates from Sorted Array II.
     *
     * Copy from: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/solution/shan-chu-pai-xu-shu-zu-zhong-de-zhong-fu-xiang-i-7/[删除排序数组中的重复项 II - 删除排序数组中的重复项 II - 力扣(LeetCode)]
     */
    public int removeDuplicates(int[] nums) {
        int j = 1, count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i - 1] == nums[i]) {
                count++;
            } else {
                count = 1;
            }
            if (count <= 2) {
                nums[j++] = nums[i];
            }
        }
        return j;
    }

    public static void main(String[] args) {
        _0080_RemoveDuplicatesFromSortedArrayII solution = new _0080_RemoveDuplicatesFromSortedArrayII();
        int[] n1 = {1, 1, 1, 2, 2, 3};
        int r1 = solution.removeDuplicates(n1);
        System.out.println((r1 == 5) + " : " + r1);

        int[] n2 = {0, 0, 1, 1, 1, 1, 2, 3, 3};
        int r2 = solution.removeDuplicates(n2);
        System.out.println((r2 == 7) + " : " + r2);
    }
}

81. Search in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

Follow up:

解题思路

这道题的关键是先确定哪部分有序,然后判断目标值是否在有序区间内,如果没有则再另外一部分内。

另外,需要注意的就是对重复值的处理。如果左边的值和中间值相等,直接让左边下标向前移动一下,简单有效。

参考资料

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2`,5,6,0,0,1,2]`, target = 0
Output: true

Example 2:

Input: nums = [2`,5,6,0,0,1,2]`, target = 3
Output: false

Follow up:

  • This is a follow up problem to <a href="/problems/search-in-rotated-sorted-array/description/">Search in Rotated Sorted Array</a>, where nums may contain duplicates.

  • Would this affect the run-time complexity? How and why?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 81. Search in Rotated Sorted Array II
 *
 * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/[Search in Rotated Sorted Array II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 22:13
 */
public class _0081_SearchInRotatedSortedArrayII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Search in Rotated Sorted Array II.
     * Memory Usage: 38.6 MB, less than 88.73% of Java online submissions for Search in Rotated Sorted Array II.
     *
     * Copy from: https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/zai-javazhong-ji-bai-liao-100de-yong-hu-by-reedfan/[搜索旋转排序数组 II - 搜索旋转排序数组 II - 力扣(LeetCode)]
     */
    public boolean search(int[] nums, int target) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return false;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[left] == nums[mid]) {
                left++;
                continue;
            }
            if (nums[left] < nums[mid]) {
                if (nums[left] <= target && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        _0081_SearchInRotatedSortedArrayII solution = new _0081_SearchInRotatedSortedArrayII();

        System.out.println(solution.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 0));

        System.out.println(solution.search(new int[]{2, 5, 6, 0, 0, 1, 2}, 3));
    }
}

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3

解题分析

快慢指针是个好办法!

注意推敲满指针前进的条件!

参考资料

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 82. Remove Duplicates from Sorted List II
 *
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/[Remove Duplicates from Sorted List II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 22:58
 */
public class _0082_RemoveDuplicatesFromSortedListII {

    /**
     * Runtime: 1 ms, faster than 60.61% of Java online submissions for Remove Duplicates from Sorted List II.
     * Memory Usage: 39.4 MB, less than 6.98% of Java online submissions for Remove Duplicates from Sorted List II.
     *
     * Copy from: https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/solution/kuai-man-zhi-zhen-by-powcai-2/[递归与非递归 - 删除排序链表中的重复元素 II - 力扣(LeetCode)]
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;
        while (Objects.nonNull(fast)) {
            while (Objects.nonNull(fast.next) && fast.val == fast.next.val) {
                fast = fast.next;
            }
            if (slow.next == fast) {
                slow = slow.next;
            } else {
                slow.next = fast.next;
            }
            fast = fast.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        _0082_RemoveDuplicatesFromSortedListII solution = new _0082_RemoveDuplicatesFromSortedListII();
        printListNode(solution.deleteDuplicates(build(asList(1, 2, 3, 3, 4, 4, 5))));
    }
}

83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3

解题分析

思考如何把代码写的简单易懂。

附加题

如果效仿 80. Remove Duplicates from Sorted Array II 要求每个元素保留不得两个,又该怎么做呢?

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 83. Remove Duplicates from Sorted List
 *
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list/[Remove Duplicates from Sorted List - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 22:39
 */
public class _0083_RemoveDuplicatesFromSortedList {

    /**
     * Runtime: 1 ms, faster than 22.08% of Java online submissions for Remove Duplicates from Sorted List.
     * Memory Usage: 40 MB, less than 7.14% of Java online submissions for Remove Duplicates from Sorted List.
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current = head.next;
        while (Objects.nonNull(current) && Objects.nonNull(current.next)) {
            if (current.val == current.next.val) {
                current.next = current.next.next;
            } else {
                current = current.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        _0083_RemoveDuplicatesFromSortedList solution = new _0083_RemoveDuplicatesFromSortedList();
        printListNode(solution.deleteDuplicates(build(asList(1, 2, 2, 3, 3, 3))));
    }
}

84. Largest Rectangle in Histogram

Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

histogram

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

histogram area

The largest rectangle is shown in the shaded area, which has area = 10 unit.

Example:

Input: [2,1,5,6,2,3]
Output: 10
1
Unresolved directive in 0084-largest-rectangle-in-histogram.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0084_LargestRectangleInHistogram.java[]

85. Maximal Rectangle

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6
1
Unresolved directive in 0085-maximal-rectangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0085_MaximalRectangle.java[]

86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

解题分析

思路很简单,直接双指针维护大小两个队列就好。

0086 1
0086 2
0086 3
0086 4
0086 5

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 86. Partition List
 *
 * https://leetcode.com/problems/partition-list/[Partition List - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 19:14
 */
public class _0086_PartitionList {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
     * Memory Usage: 37.5 MB, less than 5.77% of Java online submissions for Partition List.
     */
    public ListNode partition(ListNode head, int x) {
        if (Objects.isNull(head)) {
            return null;
        }
        ListNode dummySmall = new ListNode(0);
        ListNode dummyLarge = new ListNode(0);
        ListNode tailSmall = dummySmall;
        ListNode tailLarge = dummyLarge;
        while (Objects.nonNull(head)) {
            if (head.val < x) {
                tailSmall.next = head;
                tailSmall = tailSmall.next;
            } else {
                tailLarge.next = head;
                tailLarge = tailLarge.next;
            }
            head = head.next;
        }
        tailLarge.next = null;
        tailSmall.next = dummyLarge.next;

        return dummySmall.next;
    }

    public static void main(String[] args) {
        _0086_PartitionList solution = new _0086_PartitionList();
        printListNode(solution.partition(build(asList(1, 4, 3, 2, 5, 2)), 3));
    }
}

87. Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representation of s1 = "great":

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

We say that "rgeat" is a scrambled string of "great".

Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".

    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a

We say that "rgtae" is a scrambled string of "great".

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

Example 1:

Input: s1 = "great", s2 = "rgeat"
Output: true

Example 2:

Input: s1 = "abcde", s2 = "caebd"
Output: false
1
Unresolved directive in 0087-scramble-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0087_ScrambleString.java[]

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.

  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 88. Merge Sorted Array
 *
 * https://leetcode.com/problems/merge-sorted-array/[Merge Sorted Array - LeetCode]
 *
 * Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
 *
 * *Note:*
 *
 * * The number of elements initialized in nums1 and nums2 are m and n respectively.
 * * You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
 *
 * .Example:
 * [source]
 * ----
 * Input:
 * nums1 = [1,2,3,0,0,0], m = 3
 * nums2 = [2,5,6],       n = 3
 *
 * Output: [1,2,2,3,5,6]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-25 00:43
 */
public class _0088_MergeSortedArray {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Sorted Array.
     *
     * Memory Usage: 36.5 MB, less than 100.00% of Java online submissions for Merge Sorted Array.
     */
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if (n == 0) {
            return;
        }
        if (m == 0) {
            for (int i = 0; i < n; i++) {
                nums1[i] = nums2[i];
            }
            return;
        }
        int mi = m - 1;
        int ni = n - 1;
        int i = m + n - 1;
        while (mi >= 0 && ni >= 0) {
            if (nums1[mi] > nums2[ni]) {
                nums1[i] = nums1[mi];
                i--;
                mi--;
            } else {
                nums1[i] = nums2[ni];
                i--;
                ni--;
            }
        }
        while (ni >= 0) {
            nums1[i] = nums2[ni];
            i--;
            ni--;
        }
    }

    public static void main(String[] args) {
        _0088_MergeSortedArray solution = new _0088_MergeSortedArray();
        int[] nums1 = {1, 2, 3, 0, 0, 0};
        solution.merge(nums1, 3, new int[]{2, 5, 6}, 3);
        System.out.println(Arrays.toString(nums1));
    }
}

89. Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2^n^, which for n = 0 the size is 2^0^ = 1.
Therefore, for n = 0 the gray code sequence is [0].

解题分析

  • 设 n 阶格雷码集合为 G(n),则 G(n+1) 阶格雷码为:

    • 给 G(n) 阶格雷码每个元素二进制形式前面添加 0,得到 G'(n) ;

    • 设 G(n) 集合倒序(镜像)为 R(n),给 R(n) 每个元素二进制形式前面添加 1,得到 R'(n);

    • G(n+1) = G'(n) ∪ R'(n) 拼接两个集合即可得到下一阶格雷码。

  • 根据以上规律,可从 0 阶格雷码推导致任何阶格雷码。

  • 代码解析:

    • 由于最高位前默认为 00,因此 G'(n) = G(n),只需在 res(即 G(n) )后添加 R'(n)即可;

    • 计算 R'(n):执行 head = 1 << i 计算出对应位数,以给 R(n) 前添加 1 得到对应 R'(n);

    • 倒序遍历 res(即 G(n) ):依次求得 R'(n) 各元素添加至 res 尾端,遍历完成后 res(即 G(n+1))。

0089 1
0089 2
0089 3

这个题的解法跟 338. Counting Bits 有异曲同工之妙!

参考资料

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

Example 1:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

00 - 0
10 - 2
11 - 3
01 - 1

Example 2:

Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
             A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
             Therefore, for n = 0 the gray code sequence is [0].
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * = 89. Gray Code
 *
 * https://leetcode.com/problems/gray-code/[Gray Code - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 19:36
 */
public class _0089_GrayCode {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Gray Code.
     * Memory Usage: 37 MB, less than 8.00% of Java online submissions for Gray Code.
     *
     * Copy from: https://leetcode-cn.com/problems/gray-code/solution/gray-code-jing-xiang-fan-she-fa-by-jyd/[Gray Code (镜像反射法,图解) - 格雷编码 - 力扣(LeetCode)]
     */
    public List<Integer> grayCode(int n) {
        List<Integer> result = new ArrayList<>((int) Math.pow(2, n));
        result.add(0);
        int head = 1;
        for (int i = 0; i < n; i++) {
            for (int j = result.size() - 1; j >= 0; j--) {
                result.add(head + result.get(j));
            }
            head <<= 1;
        }
        return result;
    }

    public static void main(String[] args) {
        _0089_GrayCode solution = new _0089_GrayCode();
        System.out.println(Arrays.toString(solution.grayCode(4).toArray()));
    }
}

90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:
Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解题分析

这道题跟 78. Subsets 类似。不一样的地方是要处理重复元素:

0090 1

第 4 行新添加的 2 要加到第 3 行的所有解中,而第 3 行的一部分解是旧解,一部分是新解。可以看到,我们黑色部分是由第 3 行的旧解产生的,橙色部分是由新解产生的。

而第 1 行到第 2 行,已经在旧解中加入了 2 产生了第 2 行的橙色部分,所以这里如果再在旧解中加 2 产生黑色部分就造成了重复。

所以当有重复数字的时候,我们只考虑上一步的新解,算法中用一个指针保存每一步的新解开始的位置即可。

如果使用递归回溯来解决这个问题,遇到重复的直接跳过就可以了,因为重复字段已经处理过一次了。

参考资料

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 90. Subsets II
 *
 * https://leetcode.com/problems/subsets-ii/[Subsets II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 21:28
 */
public class _0090_SubsetsII {
    /**
     * Runtime: 2 ms, faster than 27.76% of Java online submissions for Subsets II.
     * Memory Usage: 39.4 MB, less than 5.88% of Java online submissions for Subsets II.
     */
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(nums, 0, new ArrayDeque<>(), result);
        return result;
    }

    private void backtrack(int[] nums, int start, Deque<Integer> current, List<List<Integer>> result) {
        result.add(new ArrayList<>(current));
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i - 1] == nums[i]) {
                continue;
            }
            int num = nums[i];
            current.addLast(num);
            backtrack(nums, i + 1, current, result);
            current.removeLast();
        }
    }

    /**
     * Runtime: 2 ms, faster than 27.76% of Java online submissions for Subsets II.
     * Memory Usage: 39.3 MB, less than 5.88% of Java online submissions for Subsets II.
     *
     * Copy from: https://leetcode-cn.com/problems/subsets-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-19/[详细通俗的思路分析,多解法 - 子集 II - 力扣(LeetCode)]
     */
    public List<List<Integer>> subsetsWithDupAppend(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(Collections.emptyList());
        Arrays.sort(nums);
        //保存新解的开始位置
        int start = 1;
        for (int i = 0; i < nums.length; i++) {
            List<List<Integer>> temp = new LinkedList<>();
            for (int j = 0; j < result.size(); j++) {
                //如果出现重复数字,就跳过所有旧解
                if (i > 0 && nums[i - 1] == nums[i] && j < start) {
                    continue;
                }
                List<Integer> list = result.get(j);
                List<Integer> newList = new ArrayList<>(list);
                newList.add(nums[i]);
                temp.add(newList);
            }
            start = result.size();
            result.addAll(temp);
        }
        return result;
    }

    public static void main(String[] args) {
        _0090_SubsetsII solution = new _0090_SubsetsII();
        System.out.println(Arrays.toString(solution.subsetsWithDup(new int[]{1, 2, 2}).toArray()));
    }
}

91. Decode Ways

这道题可以使用动态规划算法解决。学习《算法导论》中"动态规划"的解题步骤,再推演几次这个解题方法。

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Given a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 91. Decode Ways
 *
 * https://leetcode.com/problems/decode-ways/[Decode Ways - LeetCode]
 *
 * A message containing letters from `A-Z` is being encoded to numbers using the following mapping:
 *
 * ----
 * 'A' -> 1
 * 'B' -> 2
 * ...
 * 'Z' -> 26
 * ----
 *
 * Given a *non-empty* string containing only digits, determine the total number of ways to decode it.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "12"
 * Output: 2
 * Explanation: It could be decoded as "AB" (1 2) or "L" (12).
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "226"
 * Output: 3
 * Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-18 00:20
 */
public class _0091_DecodeWays {
    /**
     * Runtime: 3 ms, faster than 19.41% of Java online submissions for Decode Ways.
     *
     * Memory Usage: 41.5 MB, less than 5.66% of Java online submissions for Decode Ways.
     *
     * Copy from: https://leetcode.com/problems/decode-ways/discuss/30357/DP-Solution-(Java)-for-reference[DP Solution (Java) for reference - LeetCode Discuss]
     */
    public int numDecodings(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return 0;
        }
        int length = s.length();
        int[] memo = new int[length + 1];
        memo[length] = 1;
        memo[length - 1] = s.charAt(length - 1) != '0' ? 1 : 0;
        for (int i = length - 2; i >= 0; i--) {
            if (s.charAt(i) == '0') {
                continue;
            } else {
                int value = Integer.parseInt(s.substring(i, i + 2));
                memo[i] = value <= 26 ? memo[i + 1] + memo[i + 2] : memo[i + 1];
            }
        }
        return memo[0];
    }

    public static void main(String[] args) {
        _0091_DecodeWays solution = new _0091_DecodeWays();

        int r4 = solution.numDecodings("27");
        System.out.println((r4 == 1) + " : " + r4);

        int r1 = solution.numDecodings("12");
        System.out.println((r1 == 2) + " : " + r1);

        int r2 = solution.numDecodings("226");
        System.out.println((r2 == 3) + " : " + r2);

        int r3 = solution.numDecodings("0");
        System.out.println((r3 == 0) + " : " + r3);
    }
}

92. Reverse Linked List II

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

解题分析

将链表拆分成三段(注意保存必要的访问节点):

  • 第一段,保存原有的顺序不变;

  • 第二段,保存反转的链表;

  • 第三段,保存反转后的链表;

最后再将三个拼接在一起。

思考题

尝试递归的解题方式。

参考资料

Reverse a linked list from position m to n. Do it in one-pass.

*Note: *1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;
import static java.util.Arrays.asList;

/**
 * = 92. Reverse Linked List II
 *
 * https://leetcode.com/problems/reverse-linked-list-ii/[Reverse Linked List II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 22:46
 */
public class _0092_ReverseLinkedListII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List II.
     * Memory Usage: 36.6 MB, less than 11.36% of Java online submissions for Reverse Linked List II.
     */
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (m == n) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode tail = dummy;
        ListNode reverseList = new ListNode(0);
        ListNode reverseTail = null;
        for (int i = 1; i <= n && Objects.nonNull(head); i++) {
            ListNode next = head.next;
            if (i < m) {
                tail = head;
            } else {
                if (i == m) {
                    reverseTail = head;
                }
                ListNode rNext = reverseList.next;
                reverseList.next = head;
                head.next = rNext;
            }
            head = next;
        }
        if (Objects.nonNull(reverseTail)) {
            reverseTail.next = head;
        }
        tail.next = reverseList.next;
        return dummy.next;
    }

    public static void main(String[] args) {
        _0092_ReverseLinkedListII solution = new _0092_ReverseLinkedListII();
        ListNode r1 = solution.reverseBetween(build(asList(1, 2, 3, 4, 5)), 2, 4);
        printListNode(r1);
    }
}

93. Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

解题分析

使用回溯,每次做一次字符串切割,如果切割的字符串符合 IP 的大小值,则前进一步,直到把字符串切割完毕并且正好切割四份。

0093 1

参考资料

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.diguage.algorithm.leetcode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * = 93. Restore IP Addresses
 *
 * https://leetcode.com/problems/restore-ip-addresses/[Restore IP Addresses - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-06 10:00
 */
public class _0093_RestoreIPAddresses {
    /**
     * Runtime: 2 ms, faster than 88.51% of Java online submissions for Restore IP Addresses.
     * Memory Usage: 38.4 MB, less than 30.23% of Java online submissions for Restore IP Addresses.
     */
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        backtrack(s, 0, new ArrayDeque<>(), result);
        return result;
    }

    private void backtrack(String s, int start, Deque<String> current, List<String> result) {
        if (start == s.length() && current.size() == 4) {
            result.add(String.join(".", current));
            return;
        }
        for (int i = start + 1; i <= s.length() && i <= start + 3 && current.size() < 4; i++) {
            String substring = s.substring(start, i);
            if (substring.length() > 1 && substring.charAt(0) == '0') {
                continue;
            }
            int num = Integer.parseInt(substring);
            if (0 <= num && num <= 255) {
                current.addLast(substring);
                backtrack(s, i, current, result);
                current.removeLast();
            }
        }
    }

    public static void main(String[] args) {
        _0093_RestoreIPAddresses solution = new _0093_RestoreIPAddresses();
        System.out.println(solution.restoreIpAddresses("010010"));
        System.out.println(solution.restoreIpAddresses("0000"));
        System.out.println(solution.restoreIpAddresses("25525511135"));
    }
}

94. Binary Tree Inorder Traversal

迭代的方式,还不是很理解,还需要再思考思考。

Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;
import com.diguage.algorithm.util.TreeNodeUtils;

import java.util.*;

/**
 * = 94. Binary Tree Inorder Traversal
 *
 * https://leetcode.com/problems/binary-tree-inorder-traversal/[Binary Tree Inorder Traversal - LeetCode]
 *
 * Given a binary tree, return the inorder traversal of its nodes' values.
 *
 * .Example:
 * [source]
 * ----
 * Input: [1,null,2,3]
 *    1
 *     \
 *      2
 *     /
 *    3
 *
 * Output: [1,3,2]
 * ----
 *
 * *Follow up:* Recursive solution is trivial, could you do it iteratively?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-06 22:14
 */
public class _0094_BinaryTreeInorderTraversal {

  public List<Integer> inorderTraversal(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    List<Integer> result = new LinkedList<>();
    TreeNode head = root;
    while (head != null || !stack.empty()) {
      if (head != null) {
        stack.push(head);
        head = head.left;
      } else {
        head = stack.pop();
        result.add(head.val);
        head = head.right;
      }
    }
    return result;
  }
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Binary Tree Inorder Traversal.
     *
     * Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Binary Tree Inorder Traversal.
     */
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode current = root;
        while (Objects.nonNull(current) || !stack.isEmpty()) {
            while (Objects.nonNull(current)) {
                stack.push(current);
                current = current.left;
            }
            current = stack.pop();
            result.add(current.val);
            current = current.right;
        }
        return result;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Binary Tree Inorder Traversal.
     *
     * Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Binary Tree Inorder Traversal.
     */
    public List<Integer> inorderTraversalRecursion(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorderTraversal(root, result);
        return result;
    }

    public void inorderTraversal(TreeNode root, List<Integer> result) {
        if (Objects.isNull(root)) {
            return;
        }
        inorderTraversal(root.left, result);
        result.add(root.val);
        inorderTraversal(root.right, result);
    }

    public static void main(String[] args) {
        _0094_BinaryTreeInorderTraversal solution = new _0094_BinaryTreeInorderTraversal();
        TreeNode a1 = TreeNodeUtils.buildTree(Arrays.asList(1, null, 2, null, null, 3));
        List<Integer> r1 = solution.inorderTraversal(a1);
        System.out.println(Arrays.toString(r1.toArray()));
    }
}

95. Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 …​ n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
1
Unresolved directive in 0095-unique-binary-search-trees-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0095_UniqueBinarySearchTreesII.java[]

96. Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 …​ n?

Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

给定一个有序序列 1 …​ n,为了根据序列构建一棵二叉搜索树。我们可以遍历每个数字 i,将该数字作为树根,1 …​ (i-1) 序列将成为左子树,(i+1) …​ n 序列将成为右子树。于是,我们可以递归地从子序列构建子树。

在上述方法中,由于根各自不同,每棵二叉树都保证是独特的。

可见,问题可以分解成规模较小的子问题。因此,我们可以存储并复用子问题的解,而不是递归的(也重复的)解决这些子问题,这就是动态规划法。

给定序列 1 …​ n,我们选出数字 i 作为根,则对于根 i 的不同二叉搜索树数量 \(F(i, n)\),是左右子树个数的笛卡尔积,如下图所示:

0096 1

没想到这里还埋了一个数学知识:Catalan number:

\$C_{0}=1 \quad \text { and } \quad C_{n+1}=\sum_{i=0}^{n} C_{i} C_{n-i} \quad \text { for } n \geq 0\$

\$C_{0}=1, \quad C_{n+1}=\frac{2(2 n+1)}{n+2} C_{n}\$

附加题:参考资料显示,关于 Catalan number 有好多好玩的东西可以把玩。查资料把玩把玩。

参考资料

Given n, how many structurally unique BST’s (binary search trees) that store values 1 …​ n?

Example:

Input: 3
Output: 5
*Explanation:
*Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.diguage.algorithm.leetcode;

/**
 * = 96. Unique Binary Search Trees
 *
 * https://leetcode.com/problems/unique-binary-search-trees/[Unique Binary Search Trees - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 22:14
 */
public class _0096_UniqueBinarySearchTrees {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Binary Search Trees.
     * Memory Usage: 38.2 MB, less than 5.55% of Java online submissions for Unique Binary Search Trees.
     *
     * Copy from: https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/[不同的二叉搜索树 - 不同的二叉搜索树 - 力扣(LeetCode)]
     */
    public int numTreesCatalanNumber(int n) {
        long C = 1;
        for (int i = 0; i < n; i++) {
            C = C * 2 * (2 * i + 1) / (i + 2);
        }
        return (int) C;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Binary Search Trees.
     * Memory Usage: 36 MB, less than 5.55% of Java online submissions for Unique Binary Search Trees.
     *
     * Copy from: https://leetcode-cn.com/problems/unique-binary-search-trees/solution/bu-tong-de-er-cha-sou-suo-shu-by-leetcode/[不同的二叉搜索树 - 不同的二叉搜索树 - 力扣(LeetCode)]
     */
    public int numTrees(int n) {
        int[] g = new int[n + 1];
        g[0] = 1;
        g[1] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                g[i] += g[j - 1] * g[i - j];
            }
        }
        return g[n];
    }

    public static void main(String[] args) {
        _0096_UniqueBinarySearchTrees solution = new _0096_UniqueBinarySearchTrees();
        int r1 = solution.numTrees(3);
        System.out.println((r1 == 5) + " : " + r1);
    }
}

97. Interleaving String

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
1
Unresolved directive in 0097-interleaving-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0097_InterleavingString.java[]

98. Validate Binary Search Tree

0098 1
0098 2

思路很简单,利用搜索二叉树的定义,界定好树的上下界,然后递归比较就好。

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.

  • The right subtree of a node contains only nodes with keys greater than the node’s key.

  • Both the left and right subtrees must also be binary search trees.

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 98. Validate Binary Search Tree
 *
 * https://leetcode.com/problems/validate-binary-search-tree/[Validate Binary Search Tree - LeetCode]
 *
 * Given a binary tree, determine if it is a valid binary search tree (BST).
 *
 * Assume a BST is defined as follows:
 *
 * * The left subtree of a node contains only nodes with keys *less than* the node's key.
 * * The right subtree of a node contains only nodes with keys *greater than* the node's key.
 * * Both the left and right subtrees must also be binary search trees.
 *
 * .Example 1:
 * [source]
 * ----
 *     2
 *    / \
 *   1   3
 *
 * Input: [2,1,3]
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 *     5
 *    / \
 *   1   4
 *      / \
 *     3   6
 *
 * Input: [5,1,4,null,null,3,6]
 * Output: false
 * Explanation: The root node's value is 5 but its right child's value is 4.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 19:06
 */
public class _0098_ValidateBinarySearchTree {

    /**
     * Runtime: 1 ms, faster than 33.82% of Java online submissions for Validate Binary Search Tree.
     *
     * Memory Usage: 45.2 MB, less than 5.58% of Java online submissions for Validate Binary Search Tree.
     */
    public boolean isValidBST(TreeNode root) {
        if (Objects.isNull(root)) {
            return true;
        }
        return isValidBST(root, null, null);
    }

    private boolean isValidBST(TreeNode root, Integer lower, Integer upper) {
        if (Objects.isNull(root)) {
            return true;
        }

        int val = root.val;
        if (Objects.nonNull(lower) && val <= lower) {
            return false;
        }
        if (Objects.nonNull(upper) && upper <= val) {
            return false;
        }

        if (!isValidBST(root.left, lower, val)) {
            return false;
        }
        if (!isValidBST(root.right, val, upper)) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        _0098_ValidateBinarySearchTree solution = new _0098_ValidateBinarySearchTree();

        boolean r4 = solution.isValidBST(buildTree(Arrays.asList(3, 1, 5, 0, 2, 4, 6, null, null, null, 3)));
        System.out.println(r4);

        boolean r3 = solution.isValidBST(buildTree(Arrays.asList(10, 5, 15, null, null, 6, 20)));
        System.out.println(r3);

        boolean r1 = solution.isValidBST(buildTree(Arrays.asList(2, 1, 3)));
        System.out.println(r1);

        boolean r2 = solution.isValidBST(buildTree(Arrays.asList(5, 1, 4, null, null, 3, 6)));
        System.out.println(r2);
    }
}

99. Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Example 1:

Input: [1,3,null,null,2]

   1
  /
 3
  \
   2

Output: [3,1,null,null,2]

   3
  /
 1
  \
   2

Example 2:

Input: [3,1,4,null,null,2]

  3
 / \
1   4
   /
  2

Output: [2,1,4,null,null,3]

  2
 / \
1   4
   /
  3

Follow up:

  • A solution using O(n) space is pretty straight forward.

  • Could you devise a constant space solution?

1
Unresolved directive in 0099-recover-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0099_RecoverBinarySearchTree.java[]

100. Same Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:
Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true
Example 2:
Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false
Example 3:
Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

解题分析

解题思路很简单,就是做不停地做递归调用就好。不过,要注意的时,为了加快速度,遇到不等就返回,不需要再进行下一步操作。

思考题

尝试一下迭代的解决方案。

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 100. Same Tree
 *
 * https://leetcode.com/problems/same-tree/[Same Tree - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 09:53
 */
public class _0100_SameTree {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Same Tree.
     * Memory Usage: 36.4 MB, less than 5.75% of Java online submissions for Same Tree.
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (Objects.isNull(p) && Objects.isNull(q)) {
            return true;
        }
        if (Objects.isNull(p) || Objects.isNull(q)) {
            return false;
        }
        if (p.val != q.val) {
            return false;
        }
        boolean left = isSameTree(p.left, q.left);
        if (!left) {
            return false;
        }
        return isSameTree(p.right, q.right);
    }

    public static void main(String[] args) {
        _0100_SameTree solution = new _0100_SameTree();
        boolean r1 = solution.isSameTree(buildTree(asList(1, 2)), buildTree(asList(1, null, 2)));
        System.out.println(!r1);
    }
}

101. Symmetric Tree

为什么执行结果显示递归更快?而不是队列呢?

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:

Bonus points if you could solve it both recursively and iteratively.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;
import com.diguage.algorithm.util.TreeNodeUtils;

import java.util.*;

/**
 * = 101. Symmetric Tree
 *
 * https://leetcode.com/problems/symmetric-tree/[Symmetric Tree - LeetCode]
 *
 * Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
 *
 * For example, this binary tree `[1,2,2,3,4,4,3]` is symmetric:
 *
 * ----
 *     1
 *    / \
 *   2   2
 *  / \ / \
 * 3  4 4  3
 * ----
 *
 * But the following `[1,2,2,null,3,null,3]` is not:
 *
 * ----
 *     1
 *    / \
 *   2   2
 *    \   \
 *    3    3
 * ----
 *
 * **Note:**
 *
 * Bonus points if you could solve it both recursively and iteratively.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-02 00:20
 */
public class _0101_SymmetricTree {
    public boolean isSymmetric(TreeNode root) {
        return isMirror(root, root);
    }

    private boolean isMirror(TreeNode t1, TreeNode t2) {
        if (Objects.isNull(t1) && Objects.isNull(t2)) {
            return true;
        }
        if (Objects.isNull(t1)||Objects.isNull(t2)) {
            return false;
        }
        return (Objects.equals(t1.val, t2.val))
                && isMirror(t1.left, t2.right)
                && isMirror(t1.right, t2.left);
    }

    /**
     * Runtime: 1 ms, faster than 36.88% of Java online submissions for Symmetric Tree.
     *
     * Memory Usage: 38.9 MB, less than 43.54% of Java online submissions for Symmetric Tree.
     */
    public boolean isSymmetricIterative(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode t1 = queue.poll();
            TreeNode t2 = queue.poll();
            if (Objects.isNull(t1) && Objects.isNull(t2)) {
                continue;
            }
            if (Objects.isNull(t1) || Objects.isNull(t2)) {
                return false;
            }
            if (!Objects.equals(t1.val, t2.val)) {
                return false;
            }
            queue.add(t1.left);
            queue.add(t2.right);
            queue.add(t1.right);
            queue.add(t2.left);
        }
        return true;
    }

    /**
     * Runtime: 228 ms, faster than 36.88% of Java online submissions for Symmetric Tree.
     *
     * Memory Usage: 92.6 MB, less than 5.44% of Java online submissions for Symmetric Tree.
     */
    public boolean isSymmetricBfs(TreeNode root) {
        if (Objects.isNull(root)) {
            return true;
        }
        ArrayList<TreeNode> parent = new ArrayList<>();
        parent.add(root);
        while (!parent.isEmpty()) {
            HashSet<TreeNode> nodes = new HashSet<>(parent);
            if (nodes.size() == 1 && nodes.contains(null)) {
                return true;
            }
            ArrayList<TreeNode> children = new ArrayList<>(parent.size() * 2);
            for (TreeNode node : parent) {
                if (Objects.isNull(node)) {
                    children.add(null);
                    children.add(null);
                } else {
                    children.add(node.left);
                    children.add(node.right);
                }
            }
            for (int i = 0; i < children.size() / 2; i++) {
                TreeNode left = children.get(i);
                TreeNode right = children.get(children.size() - 1 - i);
                if (Objects.isNull(left) && Objects.isNull(right)) {
                    continue;
                }
                if (Objects.isNull(left) || Objects.isNull(right)) {
                    return false;
                }
                if (!Objects.equals(left.val, right.val)) {
                    return false;
                }
            }
            parent = children;
        }

        return true;
    }

    public static void main(String[] args) {
        _0101_SymmetricTree solution = new _0101_SymmetricTree();

        List<Integer> a1 = Arrays.asList(1, 2, 2, 3, 4, 4, 3);
        TreeNode t1 = TreeNodeUtils.buildTree(a1);
        boolean r1 = solution.isSymmetric(t1);
        System.out.println((r1 == true) + " : " + r1);

        List<Integer> a2 = Arrays.asList(1, 2, 2, null, 3, null, 3);
        TreeNode t2 = TreeNodeUtils.buildTree(a2);
        boolean r2 = solution.isSymmetric(t2);
        System.out.println((r2 == false) + " : " + r2);

        List<Integer> a3 = Arrays.asList(1, 2, 2, null, 3, 3);
        TreeNode t3 = TreeNodeUtils.buildTree(a3);
        boolean r3 = solution.isSymmetric(t3);
        System.out.println((r3 == true) + " : " + r3);
    }
}

102. Binary Tree Level Order Traversal

这个题其实很简单,只要保持需要读取值的那一层的节点就可以了。

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.*;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 102. Binary Tree Level Order Traversal
 *
 * https://leetcode.com/problems/binary-tree-level-order-traversal/[Binary Tree Level Order Traversal - LeetCode]
 *
 * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
 *
 * For example:
 * Given binary tree `[3,9,20,null,null,15,7]`,
 *
 * ----
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * ----
 *
 * return its level order traversal as:
 *
 * ----
 * [
 *   [3],
 *   [9,20],
 *   [15,7]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 20:40
 */
public class _0102_BinaryTreeLevelOrderTraversal {

    /**
     * Runtime: 3 ms, faster than 5.15% of Java online submissions for Binary Tree Level Order Traversal.
     *
     * Memory Usage: 40.2 MB, less than 5.33% of Java online submissions for Binary Tree Level Order Traversal.
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (Objects.isNull(root)) {
            return Collections.emptyList();
        }
        List<List<Integer>> result = new ArrayList<>();

        List<TreeNode> level = new ArrayList<>();
        level.add(root);
        while (!level.isEmpty()) {
            List<TreeNode> temp = new ArrayList<>();
            List<Integer> values = new ArrayList<>(level.size());
            for (TreeNode node : level) {
                values.add(node.val);
                if (Objects.nonNull(node.left)) {
                    temp.add(node.left);
                }
                if (Objects.nonNull(node.right)) {
                    temp.add(node.right);
                }
            }
            result.add(values);
            level = temp;
        }

        return result;
    }

    public static void main(String[] args) {
        _0102_BinaryTreeLevelOrderTraversal solution = new _0102_BinaryTreeLevelOrderTraversal();
        List<List<Integer>> r1 = solution.levelOrder(buildTree(Arrays.asList(3, 9, 20, null, null, 15, 7)));
        System.out.println(r1);
    }
}

103. Binary Tree Zigzag Level Order Traversal

思考题:思考一下如何使用深度优先来解决这个问题?

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.*;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 103. Binary Tree Zigzag Level Order Traversal
 *
 * https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/[Binary Tree Zigzag Level Order Traversal - LeetCode]
 *
 * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
 *
 * For example:
 * Given binary tree `[3,9,20,null,null,15,7]`,
 *
 * ----
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * ----
 *
 * return its zigzag level order traversal as:
 *
 * ----
 * [
 *   [3],
 *   [20,9],
 *   [15,7]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 21:12
 */
public class _0103_BinaryTreeZigzagLevelOrderTraversal {

    /**
     * Runtime: 1 ms, faster than 75.19% of Java online submissions for Binary Tree Zigzag Level Order Traversal.
     *
     * Memory Usage: 41.5 MB, less than 5.77% of Java online submissions for Binary Tree Zigzag Level Order Traversal.
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (Objects.isNull(root)) {
            return Collections.emptyList();
        }
        List<List<Integer>> result = new ArrayList<>();
        List<TreeNode> level = new ArrayList<>();
        level.add(root);
        boolean isReverse = false;
        while (!level.isEmpty()) {
            List<TreeNode> temp = new ArrayList<>();
            List<Integer> values = new ArrayList<>(level.size());
            for (TreeNode node : level) {
                if (isReverse) {
                    values.add(0, node.val);
                } else {
                    values.add(node.val);
                }
                if (Objects.nonNull(node.left)) {
                    temp.add(node.left);
                }
                if (Objects.nonNull(node.right)) {
                    temp.add(node.right);
                }
            }
            result.add(values);
            level = temp;
            isReverse = !isReverse;
        }
        return result;
    }

    public static void main(String[] args) {
        _0103_BinaryTreeZigzagLevelOrderTraversal solution = new _0103_BinaryTreeZigzagLevelOrderTraversal();
        List<List<Integer>> r2 = solution.zigzagLevelOrder(buildTree(Arrays.asList(1, 2, 3, 4, null, null, 5)));
        System.out.println(r2);

        List<List<Integer>> r1 = solution.zigzagLevelOrder(buildTree(Arrays.asList(3, 9, 20, null, null, 15, 7)));
        System.out.println(r1);
    }
}

104. Maximum Depth of Binary Tree

思考题:尝试使用迭代方式来解决一下。

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 104. Maximum Depth of Binary Tree
 *
 * https://leetcode.com/problems/maximum-depth-of-binary-tree/[Maximum Depth of Binary Tree - LeetCode]
 *
 * Given a binary tree, find its maximum depth.
 *
 * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
 *
 * *Note:* A leaf is a node with no children.
 *
 * *Example:*
 *
 * Given binary tree `[3,9,20,null,null,15,7]`,
 *
 * ----
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * ----
 *
 * return its depth = 3.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 22:17
 */
public class _0104_MaximumDepthOfBinaryTree {

    /**
     * Runtime: 1 ms, faster than 14.28% of Java online submissions for Maximum Depth of Binary Tree.
     *
     * Memory Usage: 40.7 MB, less than 5.38% of Java online submissions for Maximum Depth of Binary Tree.
     */
    public int maxDepth(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        int left = 0;
        if (Objects.nonNull(root.left)) {
            left = maxDepth(root.left);
        }
        int right = 0;
        if (Objects.nonNull(root.right)) {
            right = maxDepth(root.right);
        }
        return Math.max(left, right) + 1;
    }

    public static void main(String[] args) {
        _0104_MaximumDepthOfBinaryTree solution = new _0104_MaximumDepthOfBinaryTree();
        int r1 = solution.maxDepth(buildTree(Arrays.asList(3, 9, 20, null, null, 15, 7)));
        System.out.println((r1 == 3) + " : " + r1);
    }
}

105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.TreeNode;

/**
 * = 105. Construct Binary Tree from Preorder and Inorder Traversal
 *
 * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/[Construct Binary Tree from Preorder and Inorder Traversal - LeetCode]
 *
 * Given preorder and inorder traversal of a tree, construct the binary tree.
 *
 * *Note:*
 *
 * You may assume that duplicates do not exist in the tree.
 *
 * For example, given
 *
 * ----
 * preorder = [3,9,20,15,7]
 * inorder = [9,3,15,20,7]
 * ----
 *
 * Return the following binary tree:
 *
 * ----
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-04 20:25
 */
public class _0105_ConstructBinaryTreeFromPreorderAndInorderTraversal {
    /**
     * Runtime: 10 ms, faster than 34.14% of Java online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
     *
     * Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
     *
     * Copy from: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution[My Accepted Java Solution - LeetCode Discuss]
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, inorder, 0, 0, inorder.length);
    }

    private TreeNode build(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd) {
        if (preStart > preorder.length - 1 || inStart > inEnd) {
            return null;
        }
        int value = preorder[preStart];
        int index = inStart;
        for (int i = inStart; i <= inEnd; i++) {
            if (inorder[i] == value) {
                index = i;
                break;
            }
        }
        TreeNode root = new TreeNode(value);
        root.left = build(preorder, inorder, preStart + 1, inStart, index - 1);
        root.right = build(preorder, inorder, preStart + (index - inStart) + 1, index + 1, inEnd);
        return root;
    }

    public static void main(String[] args) {
        _0105_ConstructBinaryTreeFromPreorderAndInorderTraversal solution = new _0105_ConstructBinaryTreeFromPreorderAndInorderTraversal();
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        TreeNode tree = solution.buildTree(preorder, inorder);
        System.out.println(JsonUtils.toJson(tree));
    }
}

106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

解题分析

使用递归,从底层向上构建整个树。

0106 1
0106 2

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import static com.diguage.algorithm.util.JsonUtils.toJson;

/**
 * = 106. Construct Binary Tree from Inorder and Postorder Traversal
 *
 * https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/[Construct Binary Tree from Inorder and Postorder Traversal - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-06 21:56
 */
public class _0106_ConstructBinaryTreeFromInorderAndPostorderTraversal {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
     * Memory Usage: 41.3 MB, less than 14.54% of Java online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return buildTree(inorder, postorder, 0, inorder.length - 1, postorder.length - 1);
    }

    private TreeNode buildTree(int[] inorder, int[] postorder, int instart, int inend, int postend) {
        if (postend < 0 || instart > inend) {
            return null;
        }
        int val = postorder[postend];
        int index = inend;
        for (; index >= instart; index--) {
            if (inorder[index] == val) {
                break;
            }
        }
        TreeNode result = new TreeNode(val);
        result.left = buildTree(inorder, postorder, instart, index - 1, postend - (inend - index) - 1);
        result.right = buildTree(inorder, postorder, index + 1, inend, postend - 1);
        return result;
    }

    public static void main(String[] args) {
        _0106_ConstructBinaryTreeFromInorderAndPostorderTraversal
                solution = new _0106_ConstructBinaryTreeFromInorderAndPostorderTraversal();
        TreeNode r1 = solution.buildTree(new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3});
        System.out.println(toJson(r1));
    }
}

107. Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

   3
  / \
 9  20
   /  \
  15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

解题分析

分层访问,然后再把顺序反转过来。

思考题

尝试一下递归的解法!

参考资料

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.PrintUtils;
import com.diguage.algorithm.util.TreeNode;

import java.util.*;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 107. Binary Tree Level Order Traversal II
 *
 * https://leetcode.com/problems/binary-tree-level-order-traversal-ii/[Binary Tree Level Order Traversal II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-05 23:20
 */
public class _0107_BinaryTreeLevelOrderTraversalII {

    /**
     * Runtime: 1 ms, faster than 86.28% of Java online submissions for Binary Tree Level Order Traversal II.
     * Memory Usage: 38.8 MB, less than 5.00% of Java online submissions for Binary Tree Level Order Traversal II.
     */
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (Objects.isNull(root)) {
            return Collections.emptyList();
        }
        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            List<Integer> nums = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode node = deque.removeFirst();
                nums.add(node.val);
                if (Objects.nonNull(node.left)) {
                    deque.addLast(node.left);
                }
                if (Objects.nonNull(node.right)) {
                    deque.addLast(node.right);
                }
            }
            result.add(nums);
        }
        Collections.reverse(result);
        return result;
    }

    public static void main(String[] args) {
        _0107_BinaryTreeLevelOrderTraversalII solution = new _0107_BinaryTreeLevelOrderTraversalII();
        List<List<Integer>> r1 = solution.levelOrderBottom(buildTree(asList(3, 9, 20, null, null, 15, 7)));
        PrintUtils.printMatrix(r1);
    }
}

108. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:
Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

解题分析

代码还可以再简化一下。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

/**
 * = 108. Convert Sorted Array to Binary Search Tree
 *
 * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/[Convert Sorted Array to Binary Search Tree - LeetCode]
 *
 * Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 *
 * For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
 *
 * .Example:
 * [source]
 * ----
 * Given the sorted array: [-10,-3,0,5,9],
 *
 * One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
 *
 *       0
 *      / \
 *    -3   9
 *    /   /
 *  -10  5
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 22:28
 */
public class _0108_ConvertSortedArrayToBinarySearchTree {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Convert Sorted Array to Binary Search Tree.
     *
     * Memory Usage: 47 MB, less than 5.16% of Java online submissions for Convert Sorted Array to Binary Search Tree.
     */
    public TreeNode sortedArrayToBST(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return null;
        }
        int high = nums.length;
        int mid = high / 2;
        TreeNode root = new TreeNode(nums[mid]);
        build(root, true, nums, 0, mid - 1);
        build(root, false, nums, mid + 1, high - 1);
        return root;
    }

    private void build(TreeNode root, boolean isLeft, int[] nums, int low, int high) {
        if (low > high) {
            return;
        }
        int mid = low + (high - low) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        if (isLeft) {
            root.left = node;
        } else {
            root.right = node;
        }
        build(node, true, nums, low, mid - 1);
        build(node, false, nums, mid + 1, high);
    }

    public static void main(String[] args) {
        _0108_ConvertSortedArrayToBinarySearchTree solution = new _0108_ConvertSortedArrayToBinarySearchTree();
        int[] n1 = {-10, -3, 0, 5, 9};
        TreeNode r1 = solution.sortedArrayToBST(n1);
        System.out.println(JsonUtils.toJson(r1));
    }
}

109. Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:
Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

解题分析

这道题跟 108. Convert Sorted Array to Binary Search Tree 类似。可以转化成数组(或链表)进行求解。这属于空间换时间的解法。

另外一种解法,就是使用快满指针,找到中间节点,然后再构造二叉树。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.ListNode;
import com.diguage.algorithm.util.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static java.util.Arrays.asList;

/**
 * = 109. Convert Sorted List to Binary Search Tree
 *
 * https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/[LeetCode - Convert Sorted List to Binary Search Tree]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-06 22:42
 */
public class _0109_ConvertSortedListToBinarySearchTree {

    /**
     * Runtime: 1 ms, faster than 68.60% of Java online submissions for Convert Sorted List to Binary Search Tree.
     * Memory Usage: 41.1 MB, less than 5.26% of Java online submissions for Convert Sorted List to Binary Search Tree.
     */
    public TreeNode sortedListToBST(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        List<Integer> nums = new ArrayList<>();
        while (Objects.nonNull(head)) {
            nums.add(head.val);
            head = head.next;
        }
        return buildTree(nums, 0, nums.size());
    }

    private TreeNode buildTree(List<Integer> nums, int start, int end) {
        if (start > end || start >= nums.size()) {
            return null;
        }
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(nums.get(mid));
        root.left = buildTree(nums, start, mid - 1);
        root.right = buildTree(nums, mid + 1, end);
        return root;
    }

    public static void main(String[] args) {
        _0109_ConvertSortedListToBinarySearchTree solution = new _0109_ConvertSortedListToBinarySearchTree();
        TreeNode r1 = solution.sortedListToBST(build(asList(-10, -3, 0, 5, 9)));
        System.out.println(JsonUtils.toJson(r1));
    }
}

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:
Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

解题分析

  • 对二叉树做深度优先遍历DFS,递归过程中:

    • 终止条件:当DFS越过叶子节点时,返回高度0;

    • 返回值:

      • 从底至顶,返回以每个节点 root 为根节点的子树最大高度(左右子树中最大的高度值加1 max(left,right) + 1)

      • 当我们发现有一例 左/右子树高度差 > 1 的情况时,代表此树不是平衡树,返回 -1

    • 当发现不是平衡树时,后面的高度计算都没有意义了,因此一路返回-1,避免后续多余计算。

  • 最差情况是对树做一遍完整DFS,时间复杂度为 O(N)。

这里有个思维误区:并不是最顶层的左右树相差不超过 1 就是平衡树;而是递归定义的,是每棵树的左右子树的高度差都不能超过 1 才可以。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 110. Balanced Binary Tree
 *
 * https://leetcode.com/problems/balanced-binary-tree/[LeetCode - Balanced Binary Tree]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-06 23:10
 */
public class _0110_BalancedBinaryTree {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Balanced Binary Tree.
     * Memory Usage: 41.4 MB, less than 11.11% of Java online submissions for Balanced Binary Tree.
     */
    public boolean isBalanced(TreeNode root) {
        return depth(root) != -1;
    }

    private int depth(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        int left = depth(root.left);
        if (left == -1) {
            return -1;
        }
        int right = depth(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
    }

    public static void main(String[] args) {
        _0110_BalancedBinaryTree solution = new _0110_BalancedBinaryTree();
        System.out.println(!solution.isBalanced(buildTree(asList(1, 2, 2, 3, null, null, 3, 4, null, null, 4))));
        System.out.println(solution.isBalanced(buildTree(asList(3, 9, 20, null, null, 15, 7))));
        System.out.println(!solution.isBalanced(buildTree(asList(1, 2, 2, 3, 3, null, null, 4, 4))));
    }
}

111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

解题分析

这里并不是简单得取每个子树最小值就行了。因为一个子树为空,但是另外一个子树能还需要遍历,需要针对不为空的树,再去遍历。

思考题

使用深度优先搜索和广度优先搜索来解决这个问题。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 111. Minimum Depth of Binary Tree
 *
 * https://leetcode.com/problems/minimum-depth-of-binary-tree/[Minimum Depth of Binary Tree - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-07 21:26
 */
public class _0111_MinimumDepthOfBinaryTree {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Minimum Depth of Binary Tree.
     * Memory Usage: 40.1 MB, less than 48.44% of Java online submissions for Minimum Depth of Binary Tree.
     */
    public int minDepth(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        if (Objects.isNull(root.left) && Objects.isNull(root.right)) {
            return 1;
        }
        int min = Integer.MAX_VALUE;
        if (Objects.nonNull(root.left)) {
            min = Math.min(minDepth(root.left), min);
        }
        if (Objects.nonNull(root.right)) {
            min = Math.min(minDepth(root.right), min);
        }
        return min + 1;
    }

    public static void main(String[] args) {
        _0111_MinimumDepthOfBinaryTree solution = new _0111_MinimumDepthOfBinaryTree();
        int r1 = solution.minDepth(buildTree(asList(3, 9, 20, null, null, 15, 7)));
        System.out.println((r1 == 2) + " : " + r1);
    }
}

112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5→4→11→2 which sum is 22.

解题分析

减去当前节点值的只,然后递归调用,到叶子节点和目标值相等即可。

注意把代码写简化点!

这道题和 129. Sum Root to Leaf Numbers 类似。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.*;
import static java.util.Arrays.*;

/**
 * = 112. Path Sum
 *
 * https://leetcode.com/problems/path-sum/[Path Sum - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-07 21:53
 */
public class _0112_PathSum {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.
     * Memory Usage: 39.1 MB, less than 5.88% of Java online submissions for Path Sum.
     */
    public boolean hasPathSum(TreeNode root, int sum) {
        if (Objects.isNull(root)) {
            return false;
        }
        sum -= root.val;
        if (  Objects.isNull(root.left) && Objects.isNull(root.right)) {
            return sum == 0;
        }
        return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
    }

    public static void main(String[] args) {
        _0112_PathSum solution = new _0112_PathSum();
        boolean r1 = solution.hasPathSum(buildTree(asList(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, null, null, 1)), 22);
        System.out.println(r1);
    }
}

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

解题分析

利用回溯+深度优先搜索即可解决。

这样要重点注意的是:回溯时,前进和后退要成对出现。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.*;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 113. Path Sum II
 *
 * https://leetcode.com/problems/path-sum-ii/[Path Sum II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-07 22:31
 */
public class _0113_PathSumII {

    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Path Sum II.
     * Memory Usage: 41.8 MB, less than 6.06% of Java online submissions for Path Sum II.
     */
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new LinkedList<>();
        dfs(root, sum, result, new ArrayDeque<>());
        return result;
    }

    private void dfs(TreeNode root, int sum, List<List<Integer>> result, Deque<Integer> current) {
        if (Objects.isNull(root)) {
            return;
        }
        sum -= root.val;
        current.addLast(root.val);
        if (sum == 0 && Objects.isNull(root.left) && Objects.isNull(root.right)) {
            result.add(new ArrayList<>(current));
        }
        dfs(root.left, sum, result, current);
        dfs(root.right, sum, result, current);
        current.removeLast();
    }

    public static void main(String[] args) {
        _0113_PathSumII solution = new _0113_PathSumII();
        List<List<Integer>> r1 = solution.pathSum(buildTree(asList(5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, null, 5, 1)), 22);
        System.out.println(r1);
    }
}

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

这道题本质上来讲可以说是要做一个先根遍历。但是,却可以将这个过程逆向过来,从底向上建立起关联。不可谓不精巧。

思考题:看题解中,可以逐级将左树并入到右树。尝试一下。

参考资料

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.TreeNode;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Objects;
import java.util.Queue;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 114. Flatten Binary Tree to Linked List
 *
 * https://leetcode.com/problems/flatten-binary-tree-to-linked-list/[Flatten Binary Tree to Linked List - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 23:18
 */
public class _0114_FlattenBinaryTreeToLinkedList {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.
     * Memory Usage: 38.4 MB, less than 40.00% of Java online submissions for Flatten Binary Tree to Linked List.
     *
     * Copy from: https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--26/[详细通俗的思路分析,多解法 - 二叉树展开为链表 - 力扣(LeetCode)]
     */
    private TreeNode pre;
    public void flatten(TreeNode root) {
        if (Objects.isNull(root)) {
            return;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = pre;
        root.left = null;
        pre = root;
    }

    /**
     * Runtime: 3 ms, faster than 29.55% of Java online submissions for Flatten Binary Tree to Linked List.
     * Memory Usage: 39.8 MB, less than 10.91% of Java online submissions for Flatten Binary Tree to Linked List.
     */
    public void flattenQueue(TreeNode root) {
        Queue<TreeNode> queue = new ArrayDeque<>();
        preorder(root, queue);
        TreeNode current = queue.poll();
        while (!queue.isEmpty()) {
            current.right = queue.poll();
            current.left = null;
            current = current.right;
            if (Objects.nonNull(current)) {
                current.left = null;
            }
        }
    }

    private void preorder(TreeNode root, Queue<TreeNode> queue) {
        if (Objects.isNull(root)) {
            return;
        }
        queue.add(root);
        preorder(root.left, queue);
        preorder(root.right, queue);
    }

    public static void main(String[] args) {
        _0114_FlattenBinaryTreeToLinkedList solution = new _0114_FlattenBinaryTreeToLinkedList();
        TreeNode t1 = buildTree(Arrays.asList(1, 2, 5, 3, 4, null, 6));
        solution.flatten(t1);
        System.out.println(JsonUtils.toJson(t1));
    }
}

115. Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of S which equals T.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^ ^^
rabbbit
^^ ^^
rabbbit
^ ^

Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
  ^  ^^
babgbag
    ^
1
Unresolved directive in 0115-distinct-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0115_DistinctSubsequences.java[]

116. Populating Next Right Pointers in Each Node

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node left;
  Node right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Follow up:

  • You may only use constant extra space.

  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

Example 1:

0116 0
Input: root = [1,2,3,4,5,6,7]
Output: [1,,2,3,,4,5,6,7,]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '' signifying the end of each level.

Constraints:

  • The number of nodes in the given tree is less than 4096.

  • -1000 ⇐ node.val ⇐ 1000

解题分析

这道题和 117. Populating Next Right Pointers in Each Node II 算是姊妹题。

0116 1
0116 2

这道题的关键是在上层遍历中,把下层的链接关系建立起来。

因为是完全二叉树。所以,如果左下节点为空则到达最后一层;向右节点为空,则到达行尾需要换行。

参考资料

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 116. Populating Next Right Pointers in Each Node
 *
 * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/[Populating Next Right Pointers in Each Node - LeetCode]
 *
 * You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
 *
 * [source,cpp]
 * ----
 * struct Node {
 *   int val;
 *   Node *left;
 *   Node *right;
 *   Node *next;
 * }
 * ----
 *
 * Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
 *
 * Initially, all next pointers are set to `NULL`.
 *
 * *Follow up:*
 *
 * * You may only use constant extra space.
 * * Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
 *
 * .Example:
 * [source]
 * ----
 * Input: root = [1,2,3,4,5,6,7]
 * Output: [1,#,2,3,#,4,5,6,7,#]
 * Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
 * ----
 *
 * *Constraints:*
 *
 * * The number of nodes in the given tree is less than `4096`.
 * * `-1000 <= node.val <= 1000`
 *
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 23:06
 */
public class _0116_PopulatingNextRightPointersInEachNode {
    /**
     * Runtime: 1 ms, faster than 47.22% of Java online submissions for Populating Next Right Pointers in Each Node.
     *
     * Memory Usage: 48.3 MB, less than 6.35% of Java online submissions for Populating Next Right Pointers in Each Node.
     *
     * Copy from: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--27/[详细通俗的思路分析,多解法 - 填充每个节点的下一个右侧节点指针 - 力扣(LeetCode)]
     */
    public Node connect(Node root) {
        if (Objects.isNull(root)) {
            return root;
        }

        Node start = root;
        Node previous = root;
        Node current = null;
        while (Objects.nonNull(previous.left)) {
            if (Objects.isNull(current)) {
                previous.left.next = previous.right;
                previous = start.left;
                current = start.right;
                start = previous;
            } else {
                previous.left.next = previous.right;
                previous.right.next = current.left;
                previous = previous.next;
                current = current.next;
            }
        }
        return root;
    }

    public static void main(String[] args) {

    }


    public static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}

117. Populating Next Right Pointers in Each Node II

Given a binary tree

struct Node {
  int val;
  Node left;
  Node right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Follow up:

  • You may only use constant extra space.

  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

Example 1:

0117 1
Input: root = [1,2,3,4,5,null,7]
Output: [1,,2,3,,4,5,7,]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '' signifying the end of each level.

Constraints:

  • The number of nodes in the given tree is less than 6000.

  • -100 ⇐ node.val ⇐ 100

解题分析

这道题和 116. Populating Next Right Pointers in Each Node 算是姊妹题。

最简单的方式,使用 Deque 来保存每一层节点,然后建立起来"连接"。但是,很明显,这种方案不符合空间复杂度要求。

基于上面这种解法,再深入思考一步,上面使用 Deque 就是想要保存接下来需要访问的元素,并且保存访问的前后顺序。现在 Node 上有 next 字段,可以利用这个字段,打通这条链表,遍历上一层时,打通下一次的链接结构。这里需要保存的就有两点:

  1. 这条链表的头结点,用于下一层的遍历;

  2. 这条链表的尾节点,用于添加下一个节点。

0117 2

这样,把第一种解法的代码稍作修改就可以了。

参考资料

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-09 23:17
 */
public class _0117_PopulatingNextRightPointersInEachNodeII {

    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node(int x) {
            this.val = x;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }


    /**
     * Runtime: 1 ms, faster than 49.14% of Java online submissions for Populating Next Right Pointers in Each Node II.
     * Memory Usage: 41.4 MB, less than 100.00% of Java online submissions for Populating Next Right Pointers in Each Node II.
     *
     * Copy from: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-28/[详细通俗的思路分析,多解法 - 填充每个节点的下一个右侧节点指针 II - 力扣(LeetCode)]
     */
    public Node connect(Node root) {
        Node curr = root;
        while (Objects.nonNull(curr)) {
            Node dummy = new Node(0);
            Node tail = dummy;
            while (Objects.nonNull(curr)) {
                if (Objects.nonNull(curr.left)) {
                    tail.next = curr.left;
                    tail = tail.next;
                }
                if (Objects.nonNull(curr.right)) {
                    tail.next = curr.right;
                    tail = tail.next;
                }
                curr = curr.next;
            }
            curr = dummy.next;
        }
        return root;
    }

    /**
     * Runtime: 1 ms, faster than 49.14% of Java online submissions for Populating Next Right Pointers in Each Node II.
     * Memory Usage: 40.8 MB, less than 100.00% of Java online submissions for Populating Next Right Pointers in Each Node II.
     */
    public Node connectDeque(Node root) {
        if (Objects.isNull(root)) {
            return null;
        }
        Deque<Node> deque = new LinkedList<>();
        deque.addLast(root);
        Node prev = null;
        while (!deque.isEmpty()) {
            int size = deque.size();
            for (int i = 0; i < size; i++) {
                Node curr = deque.removeFirst();
                if (Objects.nonNull(curr.left)) {
                    deque.addLast(curr.left);
                }
                if (Objects.nonNull(curr.right)) {
                    deque.addLast(curr.right);
                }
                if (i > 0) {
                    prev.next = curr;
                }
                prev = curr;
            }
        }
        return root;
    }

    public static void main(String[] args) {
        _0117_PopulatingNextRightPointersInEachNodeII solution = new _0117_PopulatingNextRightPointersInEachNodeII();
        TreeNode treeNode = buildTree(asList(1, 2, 3, 4, 5, null, 7));
        Node node = convert(treeNode);
        Node r1 = solution.connect(node);
        System.out.println(r1);
    }

    private static Node convert(TreeNode treeNode) {
        if (Objects.isNull(treeNode)) {
            return null;
        }
        Node node = new Node(treeNode.val);
        node.left = convert(treeNode.left);
        node.right = convert(treeNode.right);
        return node;
    }
}

118. Pascal’s Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

PascalTriangleAnimated2

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

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * = 118. Pascal's Triangle
 *
 * https://leetcode.com/problems/pascals-triangle/[Pascal's Triangle - LeetCode]
 *
 * Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
 *
 * In Pascal's triangle, each number is the sum of the two numbers directly above it.
 *
 * .Example:
 * [source]
 * ----
 * Input: 5
 * Output:
 * [
 *      [1],
 *     [1,1],
 *    [1,2,1],
 *   [1,3,3,1],
 *  [1,4,6,4,1]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-25 01:04
 */
public class _0118_PascalSTriangle {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Pascal's Triangle.
     *
     * Memory Usage: 34 MB, less than 7.23% of Java online submissions for Pascal's Triangle.
     */
    public List<List<Integer>> generate(int numRows) {
        if (numRows < 1) {
            return Collections.emptyList();
        }
        List<List<Integer>> result = new ArrayList<>(numRows);
        result.add(Arrays.asList(1));
        for (int i = 1; i < numRows; i++) {
            List<Integer> parent = result.get(i - 1);
            int length = parent.size() + 1;
            List<Integer> current = new ArrayList<>(length);
            current.add(1);
            for (int j = 1; j < length; j++) {
                int left = parent.get(j - 1);
                int right = j >= parent.size() ? 0 : parent.get(j);
                current.add(left + right);
            }
            result.add(current);
        }

        return result;
    }

    public static void main(String[] args) {
        _0118_PascalSTriangle solution = new _0118_PascalSTriangle();
        List<List<Integer>> r1 = solution.generate(5);
        System.out.println(Arrays.deepToString(r1.toArray()));
    }
}

119. Pascal’s Triangle II

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

Note that the row index starts from 0.

PascalTriangleAnimated2

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

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * = 119. Pascal's Triangle II
 *
 * https://leetcode.com/problems/pascals-triangle-ii/[Pascal's Triangle II - LeetCode]
 *
 * Given a non-negative index k where k ≤ 33, return the kth 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:
 * [source]
 * ----
 * Input: 3
 * Output: [1,3,3,1]
 * ----
 *
 * *Follow up:*
 *
 * Could you optimize your algorithm to use only O(k) extra space?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-26 01:34
 */
public class _0119_PascalSTriangleII {
    /**
     * Runtime: 1 ms, faster than 89.02% of Java online submissions for Pascal's Triangle II.
     *
     * Memory Usage: 33.7 MB, less than 6.17% of Java online submissions for Pascal's Triangle II.
     */
    public List<Integer> getRow(int rowIndex) {
        List<Integer> result = new ArrayList<>(rowIndex * 3 / 2 + 1);
        result.add(1);
        for (int i = 1; i <= rowIndex; i++) {
            int left = 1;
            for (int j = 1; j < i + 1; j++) {
                int right = j == result.size() ? 0 : result.get(j);
                int element = left + right;
                if (j == result.size()) {
                    result.add(element);
                } else {
                    result.set(j, element);
                }
                left = right;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0119_PascalSTriangleII solution = new _0119_PascalSTriangleII();
        List<Integer> r1 = solution.getRow(3);
        System.out.println(Arrays.asList(1, 3, 3, 1).equals(r1) + " : " + Arrays.toString(r1.toArray()));
    }
}

120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:

Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

解题分析

0120 1

一图胜千言!

自底向上计算逐层每个元素的最小和。最后即可得出最小路径和。

思考题

尝试一下动态规划的思路。

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.diguage.algorithm.leetcode;

import java.util.List;

import static java.util.Arrays.asList;

/**
 * = 120. Triangle
 *
 * https://leetcode.com/problems/triangle/[Triangle - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-07 23:14
 */
public class _0120_Triangle {
    /**
     * Runtime: 1 ms, faster than 99.42% of Java online submissions for Triangle.
     * Memory Usage: 39.2 MB, less than 8.16% of Java online submissions for Triangle.
     */
    public int minimumTotal(List<List<Integer>> triangle) {
        int[] sums = new int[triangle.size() + 1];
        for (int i = triangle.size() - 1; i >= 0; i--) {
            List<Integer> row = triangle.get(i);
            for (int j = 0; j < row.size(); j++) {
                sums[j] = Math.min(sums[j], sums[j + 1]) + row.get(j);
            }
        }
        return sums[0];
    }

    public static void main(String[] args) {
        _0120_Triangle solution = new _0120_Triangle();
        List<List<Integer>> t1 = asList(asList(2), asList(3, 4), asList(6, 5, 7), asList(4, 1, 8, 3));
        int r1 = solution.minimumTotal(t1);
        System.out.println((r1 == 11) + " : " + r1);
    }
}

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

参考资料

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 121. Best Time to Buy and Sell Stock
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/[Best Time to Buy and Sell Stock - LeetCode]
 *
 * Say you have an array for which the ith element is the price of a given stock on day i.
 *
 * If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
 *
 * Note that you cannot sell a stock before you buy one.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [7,1,5,3,6,4]
 * Output: 5
 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
 * Not 7-1 = 6, as selling price needs to be larger than buying price.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [7,6,4,3,1]
 * Output: 0
 * Explanation: In this case, no transaction is done, i.e. max profit = 0.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-01 13:01
 */
public class _0121_BestTimeToBuyAndSellStock {
    /**
     * Runtime: 1 ms, faster than 69.16% of Java online submissions for Best Time to Buy and Sell Stock.
     * Memory Usage: 42.6 MB, less than 5.31% of Java online submissions for Best Time to Buy and Sell Stock.
     *
     * Copy from: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
    public int maxProfitDp(int[] prices) {
        int dp0 = 0;
        int dp1 = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            dp0 = Math.max(dp0, dp1 + prices[i]);
            dp1 = Math.max(dp1,  - prices[i]);
        }
        return dp0;
    }
    /**
     * Runtime: 3 ms, faster than 19.73% of Java online submissions for Best Time to Buy and Sell Stock.
     * Memory Usage: 42.7 MB, less than 5.31% of Java online submissions for Best Time to Buy and Sell Stock.
     *
     * Copy from: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
    public int maxProfitDpTable(int[] prices) {
        if (Objects.isNull(prices) || prices.length == 0) {
            return 0;
        }
        int length = prices.length;
        int[][] dp = new int[length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
        }
        return dp[length - 1][0];
    }
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Best Time to Buy and Sell Stock.
     *
     * Memory Usage: 37.3 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock.
     */
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else if (prices[i] - minPrice > maxProfit) {
                maxProfit = prices[i] - minPrice;
            }
        }
        return maxProfit;
    }

    /**
     * Runtime: 198 ms, faster than 8.08% of Java online submissions for Best Time to Buy and Sell Stock.
     *
     * Memory Usage: 38.5 MB, less than 76.99% of Java online submissions for Best Time to Buy and Sell Stock.
     */
    public int maxProfitBruteForce(int[] prices) {
        if (Objects.isNull(prices) || prices.length < 2) {
            return 0;
        }
        int maxProfit = 0;

        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxProfit) {
                    maxProfit = profit;
                }
            }
        }
        return maxProfit;
    }

    public static void main(String[] args) {
        _0121_BestTimeToBuyAndSellStock solution = new _0121_BestTimeToBuyAndSellStock();
        int[] a3 = {2, 7, 1, 4};
        int r3 = solution.maxProfit(a3);
        System.out.println((r3 == 5) + " : " + r3);

        int[] a1 = {7, 1, 5, 3, 6, 4};
        int r1 = solution.maxProfit(a1);
        System.out.println((r1 == 5) + " : " + r1);


        int[] a2 = {7, 6, 4, 3, 1};
        int r2 = solution.maxProfit(a2);
        System.out.println((r2 == 0) + " : " + r2);
    }
}

122. Best Time to Buy and Sell Stock II

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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

参考资料

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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 122. Best Time to Buy and Sell Stock II
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/[Best Time to Buy and Sell Stock II - LeetCode]
 *
 * 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 (i.e., buy one and sell one share of the stock multiple times).
 *
 * Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [7,1,5,3,6,4]
 * Output: 7
 * Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
 *              Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [1,2,3,4,5]
 * Output: 4
 * Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
 *              Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
 *              engaging multiple transactions at the same time. You must sell before buying again.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [7,6,4,3,1]
 * Output: 0
 * Explanation: In this case, no transaction is done, i.e. max profit = 0.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-04 10:55
 */
public class _0122_BestTimeToBuyAndSellStockII {

    /**
     * Runtime: 1 ms, faster than 87.57% of Java online submissions for Best Time to Buy and Sell Stock II.
     * Memory Usage: 42.8 MB, less than 5.71% of Java online submissions for Best Time to Buy and Sell Stock II.
     *
     * Copy from: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
    public int maxProfitDp(int[] prices) {
        int dp0 = 0;
        int dp1 = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            dp0 = Math.max(dp0, dp1 + prices[i]);
            dp1 = Math.max(dp1, dp0 - prices[i]);
        }
        return dp0;
    }
    /**
     * Runtime: 1 ms, faster than 85.09% of Java online submissions for Best Time to Buy and Sell Stock II.
     *
     * Memory Usage: 37 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock II.
     */
    public int maxProfit(int[] prices) {
        if (Objects.isNull(prices) || prices.length == 0) {
            return 0;
        }
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i - 1] < prices[i]) {
                result += prices[i] - prices[i - 1];
            }
        }
        return result;
    }
    /**
     * Runtime: 1 ms, faster than 85.09% of Java online submissions for Best Time to Buy and Sell Stock II.
     *
     * Memory Usage: 37 MB, less than 100.00% of Java online submissions for Best Time to Buy and Sell Stock II.
     *
     * 我的思路,别人的代码。
     */
    public int maxProfitPeakValleyApproach(int[] prices) {
        if (Objects.isNull(prices) || prices.length == 0) {
            return 0;
        }
        int i = 0;
        int valley = prices[0];
        int peak = prices[0];
        int result = 0;
        while (i < prices.length - 1) {
            while (i < prices.length - 1 && prices[i] > prices[i + 1]) {
                i++;
            }
            valley = prices[i];
            while (i < prices.length - 1 && prices[i] < prices[i++]) {
                i++;
            }
            peak = prices[i];
            result += peak - valley;
        }

        return result;
    }

    public static void main(String[] args) {
        _0122_BestTimeToBuyAndSellStockII solution = new _0122_BestTimeToBuyAndSellStockII();

        int[] a1 = {7, 1, 5, 3, 6, 4};
        int r1 = solution.maxProfit(a1);
        System.out.println((r1 == 7) + " : " + r1);

        int[] a2 = {1, 2, 3, 4, 5};
        int r2 = solution.maxProfit(a2);
        System.out.println((r2 == 4) + " : " + r2);

        int[] a3 = {7, 6, 4, 3, 1};
        int r3 = solution.maxProfit(a3);
        System.out.println((r3 == 0) + " : " + r3);
    }
}

123. Best Time to Buy and Sell Stock III

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 at most two transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
0123 1

思考题:将表格改成变量时,还需要再思考思考。

参考资料

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 at most two transactions.

*Note: *You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 123. Best Time to Buy and Sell Stock III
 * <p>
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/[Best Time to Buy and Sell Stock III - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 20:14
 */
public class _0123_BestTimeToBuyAndSellStockIII {
    /**
     * Runtime: 2 ms, faster than 47.09% of Java online submissions for Best Time to Buy and Sell Stock III.
     * Memory Usage: 42.5 MB, less than 7.32% of Java online submissions for Best Time to Buy and Sell Stock III.
     *
     * Copy from: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
    public int maxProfit(int[] prices) {
        int dp10 = 0, dp11 = Integer.MIN_VALUE;
        int dp20 = 0, dp21 = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            dp20 = Math.max(dp20, dp21 + prices[i]);
            dp21 = Math.max(dp21, dp10 - prices[i]);
            dp10 = Math.max(dp10, dp11 + prices[i]);
            dp11 = Math.max(dp11, -prices[i]);
        }
        return dp20;
    }

    /**
     * Runtime: 5 ms, faster than 22.10% of Java online submissions for Best Time to Buy and Sell Stock III.
     * Memory Usage: 42.4 MB, less than 7.32% of Java online submissions for Best Time to Buy and Sell Stock III.
     */
    public int maxProfitDpTable(int[] prices) {
        if (Objects.isNull(prices) || prices.length == 0) {
            return 0;
        }
        int maxK = 2;
        int[][][] dp = new int[prices.length][maxK + 1][2];
        for (int i = 0; i < prices.length; i++) {
            for (int k = maxK; k >= 1; k--) {
                if (i == 0) {
                    dp[i][k][0] = 0;
                    dp[i][k][1] = -prices[i];
                    continue;
                }
                dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
                dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
            }
        }
        return dp[prices.length - 1][maxK][0];
    }

    public static void main(String[] args) {
        _0123_BestTimeToBuyAndSellStockIII solution = new _0123_BestTimeToBuyAndSellStockIII();
        int[] p1 = {3, 3, 5, 0, 0, 3, 1, 4};
        int r1 = solution.maxProfit(p1);
        System.out.println((r1 == 6) + " : " + r1);

        int[] p2 = {1, 2, 3, 4, 5};
        int r2 = solution.maxProfit(p2);
        System.out.println((r2 == 4) + " : " + r2);
    }
}

124. Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-01 23:09
 */
public class _0124_BinaryTreeMaximumPathSum {

    private int result = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        suforder(root);
        return result;
    }

    private int suforder(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        int right = Math.max(0, suforder(root.right));
        int left = Math.max(0, suforder(root.left));
        result = Math.max(result, left + root.val + right);
        return Math.max(left, right) + root.val;
    }

    public static void main(String[] args) {
        _0124_BinaryTreeMaximumPathSum solution = new _0124_BinaryTreeMaximumPathSum();
        int r1 = solution.maxPathSum(buildTree(Arrays.asList(1, 2, 3)));
        System.out.println((r1 == 6) + " : " + r1);

        int r2 = solution.maxPathSum(buildTree(Arrays.asList(-10, 9, 20, null, null, 15, 7)));
        System.out.println((r2 == 42) + " : " + r2);
    }
}

125. Valid Palindrome

基本思路就是从两边想中间挤压。记得前不久有一道题使用了相似的处理手段,容我有时间找找看!

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 125. Valid Palindrome
 *
 * https://leetcode.com/problems/valid-palindrome/[Valid Palindrome - LeetCode]
 *
 * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
 *
 * *Note:* For the purpose of this problem, we define empty string as valid palindrome.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "A man, a plan, a canal: Panama"
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "race a car"
 * Output: false
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-14 23:34
 */
public class _0125_ValidPalindrome {
    /**
     * Runtime: 3 ms, faster than 96.33% of Java online submissions for Valid Palindrome.
     *
     * Memory Usage: 38.3 MB, less than 76.78% of Java online submissions for Valid Palindrome.
     */
    public boolean isPalindrome(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return true;
        }
        int left = 0;
        int right = s.length() - 1;
        while (left <= right) {
            char lc = s.charAt(left);
            char rc = s.charAt(right);
            if (!isAlphanumberic(lc)) {
                left++;
            } else if (!isAlphanumberic(rc)) {
                right--;
            } else {
                if (Character.toLowerCase(lc) != Character.toLowerCase(rc)) {
                    return false;
                }
                left++;
                right--;
            }
        }
        return true;
    }

    private boolean isAlphanumberic(char aChar) {
        return ('a' <= aChar && aChar <= 'z') || ('A' <= aChar && aChar <= 'Z')
                || ('0' <= aChar && aChar <= '9');
    }


    public static void main(String[] args) {
        _0125_ValidPalindrome solution = new _0125_ValidPalindrome();
        System.out.println(solution.isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println(solution.isPalindrome("race a car"));
    }
}

126. Word Ladder II

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

  • Only one letter can be changed at a time

  • Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return an empty list if there is no such transformation sequence.

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

  • You may assume no duplicates in the word list.

  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: []

Explanation: The endWord "cog" is not in wordList, therefore no possible* *transformation.
1
Unresolved directive in 0126-word-ladder-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0126_WordLadderII.java[]

127. Word Ladder

通过 Word Ladder - LeetCode 讲解,竟然可以抽象成无向无权图,然后通过 Queue 将其串联起来,实在好精巧。

0127 1
0127 2

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  • Only one letter can be changed at a time.

  • Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

  • You may assume no duplicates in the word list.

  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible* *transformation.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 127. Word Ladder
 *
 * https://leetcode.com/problems/word-ladder/[Word Ladder - LeetCode]
 *
 * Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
 *
 * . Only one letter can be changed at a time.
 * . Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
 *
 * *Note:*
 *
 * * Return 0 if there is no such transformation sequence.
 * * All words have the same length.
 * * All words contain only lowercase alphabetic characters.
 * * You may assume no duplicates in the word list.
 * * You may assume beginWord and endWord are non-empty and are not the same.
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * beginWord = "hit",
 * endWord = "cog",
 * wordList = ["hot","dot","dog","lot","log","cog"]
 *
 * Output: 5
 *
 * Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
 * return its length 5.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * beginWord = "hit"
 * endWord = "cog"
 * wordList = ["hot","dot","dog","lot","log"]
 *
 * Output: 0
 *
 * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 18:43
 */
public class _0127_WordLadder {
    /**
     * Runtime: 43 ms, faster than 80.36% of Java online submissions for Word Ladder.
     *
     * Memory Usage: 49.1 MB, less than 5.11% of Java online submissions for Word Ladder.
     *
     * Copy from: https://leetcode.com/problems/word-ladder/solution/[Word Ladder solution - LeetCode]
     */
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        int L = beginWord.length();
        Map<String, List<String>> allComboDict = new HashMap<>();
        wordList.forEach(word -> {
            for (int i = 0; i < L; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i + 1, L);
                List<String> transformations = allComboDict.getOrDefault(newWord, new ArrayList<>());
                transformations.add(word);
                allComboDict.put(newWord, transformations);
            }
        });

        Queue<Pair<String, Integer>> Q = new LinkedList<>();
        Q.add(new Pair<>(beginWord, 1));
        Map<String, Boolean> visited = new HashMap<>();
        visited.put(beginWord, true);

        while (!Q.isEmpty()) {
            Pair<String, Integer> node = Q.remove();
            String word = node.getKey();
            Integer level = node.getValue();
            for (int i = 0; i < L; i++) {
                String newWord = word.substring(0, i) + "*" + word.substring(i + 1, L);
                for (String adjacentWord : allComboDict.getOrDefault(newWord, Collections.emptyList())) {
                    if (adjacentWord.equals(endWord)) {
                        return level + 1;
                    }
                    if (!visited.containsKey(adjacentWord)) {
                        visited.put(adjacentWord, true);
                        Q.add(new Pair<>(adjacentWord, level + 1));
                    }
                }
            }
        }

        return 0;
    }

    public static class Pair<K, V> {
        private K key;
        private V value;

        public Pair(K key, V value) {

        }

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        _0127_WordLadder solution = new _0127_WordLadder();
        int r1 = solution.ladderLength("hit", "cog", Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"));
        System.out.println((r1 == 5) + " : " + r1);
    }
}

128. Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
1
Unresolved directive in 0128-longest-consecutive-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0128_LongestConsecutiveSequence.java[]

129. Sum Root to Leaf Numbers

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1→2→3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.

Example 2:

Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

解题分析

这道题和 112. Path Sum 类似。

找到所有路径,父级乘以10,再加当前节点,最后到叶子节点时,加入到总和中。

思考题

  1. 尝试使用中根遍历和后跟遍历的解法。

  2. 目前解法是会用了实例变量,能否取去掉?

参考资料

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 129. Sum Root to Leaf Numbers
 *
 * https://leetcode.com/problems/sum-root-to-leaf-numbers/[Sum Root to Leaf Numbers - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-07 23:56
 */
public class _0129_SumRootToLeafNumbers {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum Root to Leaf Numbers.
     * Memory Usage: 37.7 MB, less than 5.13% of Java online submissions for Sum Root to Leaf Numbers.
     */
    private int sum = 0;
    public int sumNumbers(TreeNode root) {
        dfs(root, 0);
        return sum;
    }

    private void dfs(TreeNode root, int parent) {
        if (Objects.isNull(root)) {
            return;
        }
        int temp = parent * 10 + root.val;
        if (Objects.isNull(root.left) && Objects.isNull(root.right)) {
            sum += temp;
            return;
        }
        dfs(root.left, temp);
        dfs(root.right, temp);
    }


    public static void main(String[] args) {
        _0129_SumRootToLeafNumbers solution = new _0129_SumRootToLeafNumbers();

        solution.sum = 0;
        int r1 = solution.sumNumbers(buildTree(asList(1, 2, 3)));
        System.out.println((r1 == 25) + " : " + r1);

        solution.sum = 0;
        int r2 = solution.sumNumbers(buildTree(asList(4, 9, 0, 5, 1)));
        System.out.println((r2 == 1026) + " : " + r2);
    }
}

130. Surrounded Regions

这道题的关键点在于找到入口。对我们来说,入口就是边界的的 O,然后与之相连的 O,其他的 O 都会被替换为 X。为了区别对待,可以把识别出来的 O 替换为其他的字符,比如 #。这样后期再遍历处理即可。

思考题:看题解可以使用 UnionFind 来解决这个问题。可以思考一下,如何实现?

这道题与 0200-number-of-islands.adoc 类似。

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all ’O'`s into ’X'`s in that surrounded region.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 130. Surrounded Regions
 *
 * https://leetcode.com/problems/surrounded-regions/[Surrounded Regions - LeetCode]
 *
 * Given a 2D board containing `'X'` and `'O'` (the letter O), capture all regions surrounded by `'X'`.
 *
 * A region is captured by flipping all `'O'`s into `'X'`s in that surrounded region.
 *
 * *Example:*
 *
 * ----
 * X X X X
 * X O O X
 * X X O X
 * X O X X
 * ----
 *
 * After running your function, the board should be:
 *
 * ----
 * X X X X
 * X X X X
 * X X X X
 * X O X X
 * ----
 *
 * *Explanation:*
 *
 * Surrounded regions shouldn’t be on the border, which means that any `'O'` on the border of the board are not flipped to `'X'`. Any `'O'` that is not on the border and it is not connected to an `'O'` on the border will be flipped to `'X'`. Two cells are connected if they are adjacent cells connected horizontally or vertically.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 19:57
 */
public class _0130_SurroundedRegions {
    /**
     * Runtime: 4 ms, faster than 22.25% of Java online submissions for Surrounded Regions.
     *
     * Memory Usage: 49.1 MB, less than 7.14% of Java online submissions for Surrounded Regions.
     *
     * Copy from: https://leetcode-cn.com/problems/surrounded-regions/solution/bfsdi-gui-dfsfei-di-gui-dfsbing-cha-ji-by-ac_pipe/[bfs+递归dfs+非递归dfs+并查集 - 被围绕的区域 - 力扣(LeetCode)]
     */
    public void solve(char[][] board) {
        if (Objects.isNull(board) || board.length == 0) {
            return;
        }

        int yLength = board.length;
        int xLength = board[0].length;
        for (int y = 0; y < yLength; y++) {
            for (int x = 0; x < xLength; x++) {
                boolean isEdge = y == 0 || y == yLength - 1
                        || x == 0 || x == xLength - 1;
                if (isEdge && board[y][x] == 'O') {
                    dfs(board, y, x);
                }
            }
        }

        for (int y = 0; y < yLength; y++) {
            for (int x = 0; x < xLength; x++) {
                if (board[y][x] == 'O') {
                    board[y][x] = 'X';
                }
                if (board[y][x] == '#') {
                    board[y][x] = 'O';
                }
            }
        }
    }

    private void dfs(char[][] board, int y, int x) {
        if (y < 0 || y >= board.length || x < 0 || x >= board[0].length
                || board[y][x] == 'X'
                || board[y][x] == '#') {
            return;
        }
        board[y][x] = '#';
        dfs(board, y - 1, x);
        dfs(board, y + 1, x);
        dfs(board, y, x - 1);
        dfs(board, y, x + 1);
    }


    public static void main(String[] args) {
        _0130_SurroundedRegions solution = new _0130_SurroundedRegions();
    }
}

131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
  ["aa","b"],
  ["a","a","b"]
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 131. Palindrome Partitioning
 *
 * https://leetcode.com/problems/palindrome-partitioning/[Palindrome Partitioning - LeetCode]
 *
 * Given a string s, partition s such that every substring of the partition is a palindrome.
 *
 * Return all possible palindrome partitioning of s.
 *
 * .Example:
 * [source]
 * ----
 * Input: "aab"
 * Output:
 * [
 *   ["aa","b"],
 *   ["a","a","b"]
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-04 19:04
 */
public class _0131_PalindromePartitioning {
    /**
     * Runtime: 2 ms, faster than 94.23% of Java online submissions for Palindrome Partitioning.
     * Memory Usage: 39.2 MB, less than 95.45% of Java online submissions for Palindrome Partitioning.
     *
     * Copy from: https://leetcode.com/problems/palindrome-partitioning/discuss/41963/Java%3A-Backtracking-solution.[Java: Backtracking solution. - LeetCode Discuss]
     */
    public List<List<String>> partition(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return Collections.emptyList();
        }
        List<List<String>> result = new LinkedList<>();
        List<String> current = new ArrayList<>();
        dfs(s, 0, current, result);
        return result;
    }

    private void dfs(String s, int index, List<String> current, List<List<String>> result) {
        if (index == s.length()) {
            result.add(new ArrayList<>(current));
        } else {
            for (int i = index; i < s.length(); i++) {
                if (isPalindrome(s, index, i)) {
                    current.add(s.substring(index, i + 1));
                    dfs(s, i + 1, current, result);
                    current.remove(current.size() - 1);
                }
            }
        }
    }

    private boolean isPalindrome(String s, int low, int high) {
        while (low < high) {
            if (!Objects.equals(s.charAt(low++), s.charAt(high--))) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        _0131_PalindromePartitioning solution = new _0131_PalindromePartitioning();
        String s1 = "aab";
        List<List<String>> r1 = solution.partition(s1);
        System.out.println(Arrays.deepToString(r1.toArray()));
    }
}

132. Palindrome Partitioning II

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

Example:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
1
Unresolved directive in 0132-palindrome-partitioning-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0132_PalindromePartitioningII.java[]

133. Clone Graph

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.

class Node {
    public int val;
    public List<Node> neighbors;
}

Test case format:

For simplicity sake, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.

Adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

Example 1:

0133 1 clone graph question
Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]
Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

Example 2:

0133 2 graph
Input: adjList = [[]]
Output: [[]]
Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.

Example 3:

Input: adjList = []
Output: []
Explanation: This an empty graph, it does not have any nodes.

Example 4:

0133 3 graph
Input: adjList = [[2],[1]]
Output: [[2],[1]]

Constraints:

  • 1 ⇐ Node.val ⇐ 100

  • Node.val is unique for each node.

  • Number of Nodes will not exceed 100.

  • There is no repeated edges and no self-loops in the graph.

  • The Graph is connected and all nodes can be visited starting from the given node.

解题分析

这道题可以使用类似 138. Copy List with Random Pointer 的解法来求解。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-10 00:22
 */
public class _0133_CloneGraph {
    // Definition for a Node.
    static class Node {
        public int val;
        public List<Node> neighbors;

        public Node() {
            val = 0;
            neighbors = new ArrayList<Node>();
        }

        public Node(int _val) {
            val = _val;
            neighbors = new ArrayList<Node>();
        }

        public Node(int _val, ArrayList<Node> _neighbors) {
            val = _val;
            neighbors = _neighbors;
        }
    }

    /**
     * Runtime: 28 ms, faster than 34.86% of Java online submissions for Clone Graph.
     * Memory Usage: 38.8 MB, less than 5.88% of Java online submissions for Clone Graph.
     */
    public Node cloneGraphDfs(Node node) {
        Map<Node, Node> dict = new HashMap<>();
        return dfs(node, dict);
    }

    private Node dfs(Node node, Map<Node, Node> dict) {
        if (Objects.isNull(node)) {
            return null;
        }
        if (dict.containsKey(node)) {
            return dict.get(node);
        }
        Node clone = new Node(node.val, new ArrayList<>(node.neighbors.size()));
        dict.put(node, clone);
        for (Node n : node.neighbors) {
            clone.neighbors.add(dfs(n, dict));
        }
        return clone;
    }

    /**
     * Runtime: 26 ms, faster than 47.60% of Java online submissions for Clone Graph.
     * Memory Usage: 39.3 MB, less than 5.88% of Java online submissions for Clone Graph.
     */
    public Node cloneGraph(Node node) {
        if (Objects.isNull(node)) {
            return null;
        }
        Map<Node, Node> dict = new HashMap<>();
        dict.put(node, new Node(node.val, new ArrayList<>(node.neighbors.size())));
        Deque<Node> deque = new LinkedList<>();
        deque.addLast(node);
        while (!deque.isEmpty()) {
            Node curr = deque.removeFirst();
            for (Node n : curr.neighbors) {
                if (!dict.containsKey(n)) {
                    dict.put(n, new Node(n.val, new ArrayList<>(n.neighbors.size())));
                    deque.addLast(n);
                }
                dict.get(curr).neighbors.add(dict.get(n));
            }
        }

        return dict.get(node);
    }

    public static void main(String[] args) {
        _0133_CloneGraph solution = new _0133_CloneGraph();
        solution.cloneGraph(new Node(1));
    }
}

134. Gas Station

0134 1
0134 2
0134 3

这道题首先要明白题意是什么?最关键是有几点:

  1. 总的油量是否够消耗?

  2. 首次发车的车站是否够行驶到下一个车站?

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.

  • Both input arrays are non-empty and have the same length.

  • Each element in the input arrays is a non-negative integer.

Example 1:

Input:
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3

*Explanation:
*Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.

Example 2:

Input:
gas  = [2,3,4]
cost = [3,4,3]

Output: -1

*Explanation:
*You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.diguage.algorithm.leetcode;

/**
 * = 134. Gas Station
 *
 * https://leetcode.com/problems/gas-station/[Gas Station - LeetCode]
 *
 * There are N gas stations along a circular route, where the amount of gas at station i is `gas[i]`.
 *
 * You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
 *
 * Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
 *
 * *Note:*
 *
 * * If there exists a solution, it is guaranteed to be unique.
 * * Both input arrays are non-empty and have the same length.
 * * Each element in the input arrays is a non-negative integer.
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * gas  = [1,2,3,4,5]
 * cost = [3,4,5,1,2]
 *
 * Output: 3
 *
 * Explanation:
 * Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
 * Travel to station 4. Your tank = 4 - 1 + 5 = 8
 * Travel to station 0. Your tank = 8 - 2 + 1 = 7
 * Travel to station 1. Your tank = 7 - 3 + 2 = 6
 * Travel to station 2. Your tank = 6 - 4 + 3 = 5
 * Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
 * Therefore, return 3 as the starting index.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * gas  = [2,3,4]
 * cost = [3,4,3]
 *
 * Output: -1
 *
 * Explanation:
 * You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
 * Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
 * Travel to station 0. Your tank = 4 - 3 + 2 = 3
 * Travel to station 1. Your tank = 3 - 3 + 3 = 3
 * You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
 * Therefore, you can't travel around the circuit once no matter where you start.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 21:55
 */
public class _0134_GasStation {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Gas Station.
     *
     * Memory Usage: 39.1 MB, less than 5.88% of Java online submissions for Gas Station.
     *
     * Copy from: https://leetcode-cn.com/problems/gas-station/solution/jia-you-zhan-by-leetcode/[加油站 - 加油站 - 力扣(LeetCode)]
     */
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int n = gas.length;
        int totalTank = 0;
        int currentTank = 0;
        int startStation = 0;
        for (int i = 0; i < n; i++) {
            totalTank += gas[i] - cost[i];
            currentTank += gas[i] - cost[i];
            if (currentTank < 0) {
                startStation = i + 1;
                currentTank = 0;
            }
        }
        return totalTank >= 0 ? startStation : -1;
    }

    public static void main(String[] args) {
        _0134_GasStation solution = new _0134_GasStation();
        int[] g1 = {1, 2, 3, 4, 5};
        int[] c1 = {3, 4, 5, 1, 2};
        int r1 = solution.canCompleteCircuit(g1, c1);
        System.out.println((r1 == 3) + " : " + r1);
    }
}

135. Candy

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.

  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.
1
Unresolved directive in 0135-candy.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0135_Candy.java[]

136. Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 136. Single Number
 *
 * https://leetcode.com/problems/single-number/[Single Number - LeetCode]
 *
 * Given a non-empty array of integers, every element appears twice except for one. Find that single one.
 *
 * *Note:*
 *
 * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [2,2,1]
 * Output: 1
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [4,1,2,1,2]
 * Output: 4
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-01 12:38
 */
public class _0136_SingleNumber {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Single Number.
     *
     * Memory Usage: 38.5 MB, less than 98.52% of Java online submissions for Single Number.
     */
    public int singleNumber(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int result = nums[0];
        for (int i = 1; i < nums.length; i++) {
            result ^= nums[i];
        }
        return result;
    }

    public static void main(String[] args) {
        _0136_SingleNumber solution = new _0136_SingleNumber();
        int[] a1 = {2, 2, 1};
        int r1 = solution.singleNumber(a1);
        System.out.println((r1 == 1) + " : " + r1);

        int[] a2 = {4, 1, 2, 1, 2};
        int r2 = solution.singleNumber(a2);
        System.out.println((r2 == 4) + " : " + r2);
    }
}

137. Single Number II

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99
1
Unresolved directive in 0137-single-number-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0137_SingleNumberII.java[]

138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val

  • random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.

Example 1:

0138 copy list with random pointer example 1
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2:

0138 copy list with random pointer example 2
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]

Example 3:

0138 copy list with random pointer example 3
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]

Example 4:

Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.

Constraints:

  • -10000 ⇐ Node.val ⇐ 10000

  • Node.random is null or pointing to a node in the linked list.

  • Number of Nodes will not exceed 1000.

解题分析

这道题可以使用类似 133. Clone Graph 的解法来求解。

0138 copy list with random pointer

这个解法非常精妙!

使用 Map 的解法也好巧妙啊!

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 138. Copy List with Random Pointer
 *
 * https://leetcode.com/problems/copy-list-with-random-pointer/[Copy List with Random Pointer - LeetCode]
 *
 * A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
 *
 * Return a deep copy of the list.
 *
 * The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
 *
 * * `val`: an integer representing `Node.val`
 * * `random_index`: the index of the node (range from `0` to `n-1`) where random pointer points to, or `null` if it does not point to any node.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
 * Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: head = [[1,1],[2,1]]
 * Output: [[1,1],[2,1]]
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: head = [[3,null],[3,0],[3,null]]
 * Output: [[3,null],[3,0],[3,null]]
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: head = []
 * Output: []
 * Explanation: Given linked list is empty (null pointer), so return null.
 * ----
 *
 * *Constraints:*
 *
 * * `-10000 <= Node.val <= 10000`
 * * `Node.random` is null or pointing to a node in the linked list.
 * * Number of Nodes will not exceed 1000.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-07 22:21
 */
public class _0138_CopyListWithRandomPointer {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Copy List with Random Pointer.
     *
     * Memory Usage: 40.6 MB, less than 5.61% of Java online submissions for Copy List with Random Pointer.
     *
     * Copy from: https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43488/Java-O(n)-solution[Java O(n) solution - LeetCode Discuss]
     */
    public Node copyRandomList(Node head) {
        if (Objects.isNull(head)) {
            return null;
        }
        Map<Node, Node> dadToChildMap = new HashMap<>();
        Node current = head;
        while (Objects.nonNull(current)) {
            dadToChildMap.put(current, new Node(current.val));
            current = current.next;
        }

        current = head;
        while (Objects.nonNull(current)) {
            dadToChildMap.get(current).next = dadToChildMap.get(current.next);
            dadToChildMap.get(current).random = dadToChildMap.get(current.random);
            current = current.next;
        }

        return dadToChildMap.get(head);
    }
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Copy List with Random Pointer.
     *
     * Memory Usage: 39.2 MB, less than 5.61% of Java online submissions for Copy List with Random Pointer.
     *
     * Copy form: https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43491/A-solution-with-constant-space-complexity-O(1)-and-linear-time-complexity-O(N)[A solution with constant space complexity O(1) and linear time complexity O(N) - LeetCode Discuss]
     */
    public Node copyRandomListLink(Node head) {
        if (Objects.isNull(head)) {
            return null;
        }
        // 第一步:把原始链表和结果链表混编起来。
        Node acNode = head;
        while (Objects.nonNull(acNode)) {
            Node node = new Node(acNode.val);
            node.next = acNode.next;
            acNode.next = node;
            acNode = node.next;
        }
        // 第二步:复制 random 指针
        acNode = head;
        while (Objects.nonNull(acNode)) {
            Node random = acNode.random;
            if (Objects.nonNull(random)) {
                Node next = acNode.next;
                next.random = random.next;
            }
            acNode = acNode.next.next;
        }

        // 第三步:拆分出结果链表
        // Node result = head.next;
        // Node rcNode = result;
        // acNode = head;
        // while (Objects.nonNull(rcNode)) {
        //     if (Objects.nonNull(rcNode.next)) {
        //         acNode.next = rcNode.next;
        //         rcNode.next = rcNode.next.next;
        //         acNode = acNode.next;
        //     }
        //     rcNode = rcNode.next;
        // }
        // acNode.next = null;

        Node prefixHead = new Node(0);
        Node rcNode = prefixHead;
        acNode = head;
        while (Objects.nonNull(acNode)) {
            rcNode.next = acNode.next;
            acNode.next = acNode.next.next;
            acNode = acNode.next;
            rcNode = rcNode.next;
        }

        return prefixHead.next;
    }

    public static void main(String[] args) {
        _0138_CopyListWithRandomPointer solution = new _0138_CopyListWithRandomPointer();
        Integer[][] a1 = {{7, null}, {13, 0}, {11, 4}, {10, 2}, {1, 0}};
        Node l1 = build(a1);
        Node r1 = solution.copyRandomList(l1);

        Integer[][] a2 = {{1, 1}, {2, 1}};
        Node l2 = build(a2);
        Node r2 = solution.copyRandomList(l2);
    }

    public static Node build(Integer[][] array) {
        Node restult = new Node(array[0][0]);
        Node current = restult;
        for (int i = 1; i < array.length; i++) {
            Node next = new Node(array[i][0]);
            current.next = next;
            current = next;
        }

        current = restult;
        for (int i = 0; i < array.length; i++) {
            Integer[] ints = array[i];
            if (Objects.nonNull(ints[1])) {
                Node random = restult;
                for (int j = 0; j < ints[1]; j++) {
                    random = random.next;
                }
                current.random = random;
            }
            current = current.next;
        }

        return restult;
    }

    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}

139. Word Break

TODO: 似乎明白了,又似乎不明白。

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.

  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because “applepenapple” can be segmented as “apple pen apple”.
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * = 139. Word Break
 *
 * https://leetcode.com/problems/word-break/[Word Break - LeetCode]
 *
 * Given a *non-empty* string s and a dictionary wordDict containing a list of *non-empty* words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
 *
 * *Note:*
 *
 * * The same word in the dictionary may be reused multiple times in the segmentation.
 * * You may assume the dictionary does not contain duplicate words.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: s = "leetcode", wordDict = ["leet", "code"]
 * Output: true
 * Explanation: Return true because "leetcode" can be segmented as "leet code".
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: s = "applepenapple", wordDict = ["apple", "pen"]
 * Output: true
 * Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
 *              Note that you are allowed to reuse a dictionary word.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
 * Output: false
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 09:39
 */
public class _0139_WordBreak {
    /**
     * Runtime: 11 ms, faster than 6.65% of Java online submissions for Word Break.
     *
     * Memory Usage: 44.3 MB, less than 5.08% of Java online submissions for Word Break.
     *
     * Copy from: https://leetcode-cn.com/problems/word-break/solution/dan-ci-chai-fen-by-leetcode/[单词拆分 - 单词拆分 - 力扣(LeetCode)]
     */
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];
        Arrays.fill(dp, false);
        dp[0] = true;
        Set<String> dict = new HashSet<>(wordDict);
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && dict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

    public static void main(String[] args) {
        _0139_WordBreak solution = new _0139_WordBreak();

        boolean r4 = solution.wordBreak("aaaaaaa", Arrays.asList("aaaa", "aaa"));
        System.out.println(r4);

        boolean r1 = solution.wordBreak("leetcode", Arrays.asList("leet", "code"));
        System.out.println(r1);

        boolean r2 = solution.wordBreak("applepenapple", Arrays.asList("apple", "pen"));
        System.out.println(r2);

        boolean r3 = solution.wordBreak("catsandog", Arrays.asList("cats", "dog", "sand", "and", "cat"));
        System.out.println(!r3);
    }
}

140. Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.

  • You may assume the dictionary does not contain duplicate words.

Example 1:

*Input:
*s = “catsanddog”
wordDict = ["cat", "cats", "and", "sand", "dog"]
*Output:
*[
  "cats and dog",
  "cat sand dog"
]

Example 2:

Input:
*s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
*Output:
*[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
*Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

*Input:
*s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
*Output:
*[]
1
Unresolved directive in 0140-word-break-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0140_WordBreakII.java[]

141. Linked List Cycle

除了双指针外,还可以使用 Map 来解决。只是空间复杂度要高一些。

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
circularlinkedlist

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
circularlinkedlist test2

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
circularlinkedlist test3

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;
import com.diguage.algorithm.util.ListNodeUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * = 141. Linked List Cycle
 *
 * https://leetcode.com/problems/linked-list-cycle/[Linked List Cycle - LeetCode]
 *
 * Given a linked list, determine if it has a cycle in it.
 *
 * To represent a cycle in the given linked list, we use an integer `pos` which represents the position (0-indexed) in the linked list where tail connects to. If `pos` is `-1`, then there is no cycle in the linked list.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: head = [3,2,0,-4], pos = 1
 * Output: true
 * Explanation: There is a cycle in the linked list, where tail connects to the second node.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: head = [1,2], pos = 0
 * Output: true
 * Explanation: There is a cycle in the linked list, where tail connects to the first node.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: head = [1], pos = -1
 * Output: false
 * Explanation: There is no cycle in the linked list.
 * ----
 *
 * *Follow up:*
 *
 * Can you solve it using O(1) (i.e. constant) memory?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-12 10:06
 */
public class _0141_LinkedListCycle {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
     *
     * Memory Usage: 37.9 MB, less than 84.29% of Java online submissions for Linked List Cycle.
     */
    public boolean hasCycle(ListNode head) {
        if (Objects.isNull(head)) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (Objects.nonNull(fast)) {
            if (slow == fast) {
                return true;
            }
            slow = slow.next;
            fast = fast.next;
            if (Objects.nonNull(fast)) {
                fast = fast.next;
            }
        }
        return false;
    }

    /**
     * Runtime: 5 ms, faster than 6.60% of Java online submissions for Linked List Cycle.
     *
     * Memory Usage: 38.3 MB, less than 82.14% of Java online submissions for Linked List Cycle.
     *
     * Copy from: https://leetcode.com/problems/linked-list-cycle/solution/[Linked List Cycle solution - LeetCode]
     */
    public boolean hasCycleMap(ListNode head) {
        Set<ListNode> nodes = new HashSet<>();
        ListNode current = head;
        while (Objects.nonNull(current)) {
            if (nodes.contains(current)) {
                return true;
            } else {
                nodes.add(current);
            }
            current = current.next;
        }
        return false;
    }
    public static void main(String[] args) {
        _0141_LinkedListCycle solution = new _0141_LinkedListCycle();
        ListNode l1 = ListNodeUtils.build(Arrays.asList(3, 2, 0, -4));
        l1.next.next.next.next = l1.next;
        boolean r1 = solution.hasCycle(l1);
        System.out.println(r1);
    }
}

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
0142 1
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
0142 2
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
0142 3

Follow-up:

Can you solve it without using extra space?

解题思路分析

这是 Floyd’s Tortoise and Hare (Cycle Detection) 算法。

0142 4

\begin{aligned} 2 \cdot \text { distance }(\text { tortoise }) &=\text { distance }(\text {hare}) \\ 2(F+a) &=F+a+b+a \\ 2 F+2 a &=F+2 a+b \\ F &=b \end{aligned}

这里解释一下:兔子跑的快,相遇时,兔子跑过的距离是乌龟跑过的距离的两倍。兔子沿着环,跑了一圈多,有多跑了 ` ` 才相遇,所以距离是: \(F+a+b+a\)。

这个思路还可以用于解决 287. Find the Duplicate Number

没想到有这么多环形探测算法!

附加题:尝试其他探测环形算法。

参考资料

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
circularlinkedlist

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
circularlinkedlist test2

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
circularlinkedlist test3

Follow-up:

Can you solve it without using extra space?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;

/**
 * = 142. Linked List Cycle II
 *
 * https://leetcode.com/problems/linked-list-cycle-ii/[Linked List Cycle II - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 08:52
 */
public class _0142_LinkedListCycleII {

    /**
     * Runtime: 1 ms, faster than 32.38% of Java online submissions for Linked List Cycle II.
     * Memory Usage: 41.2 MB, less than 6.32% of Java online submissions for Linked List Cycle II.
     */
    public ListNode detectCycle(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        ListNode intersect = getIntersect(head);
        if (Objects.isNull(intersect)) {
            return null;
        }
        ListNode pointer1 = head;
        ListNode pointer2 = intersect;
        while (pointer1 != pointer2) {
            pointer1 = pointer1.next;
            pointer2 = pointer2.next;
        }
        return pointer1;
    }

    private ListNode getIntersect(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        ListNode tortoise = head;
        ListNode hare = head;
        while (Objects.nonNull(hare) && Objects.nonNull(hare.next)) {
            tortoise = tortoise.next;
            hare = hare.next.next;
            if (Objects.equals(tortoise, hare)) {
                return tortoise;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        _0142_LinkedListCycleII solution = new _0142_LinkedListCycleII();
        ListNode l1 = build(Arrays.asList(3, 2, 0, -4));
        l1.next.next.next.next = l1.next;
        ListNode listNode = solution.detectCycle(l1);
        System.out.println(JsonUtils.toJson(listNode));
    }
}

143. Reorder List

Given a singly linked list L: L0→_L_1→…→_L_n-1→_L_n,

reorder it to: L0→_L_n→_L_1→_L_n-1→_L_2→_L_n-2→…

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

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
1
Unresolved directive in 0143-reorder-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0143_ReorderList.java[]

144. Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,2,3]

Follow up: Recursive solution is trivial, could you do it iteratively?

解题分析

凡是用递归能解决的问题,都可以使用遍历来解决。用递归来求解问题,无非就是使用了方法栈来保存相关信息。同样,可以使用 Stack 来自己动手维护这些信息。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Stack;

/**
 * = 144. Binary Tree Preorder Traversal
 *
 * https://leetcode.com/problems/binary-tree-preorder-traversal/[Binary Tree Preorder Traversal - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-06-16 10:59
 */
public class _0144_BinaryTreePreorderTraversal {

  /**
   * Runtime: 0 ms, faster than 100.00% of Java online submissions for Binary Tree Preorder Traversal.
   * Memory Usage: 37.4 MB, less than 92.86% of Java online submissions for Binary Tree Preorder Traversal.
   */
  public List<Integer> preorderTraversal(TreeNode root) {
    if (Objects.isNull(root)) {
      return Collections.emptyList();
    }
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    List<Integer> result = new LinkedList<>();
    while (!stack.empty()) {
      TreeNode node = stack.pop();
      result.add(node.val);
      if (Objects.nonNull(node.right)) {
        stack.push(node.right);
      }
      if (Objects.nonNull(node.left)) {
        stack.push(node.left);
      }
    }
    return result;
  }
}

145. Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

解题分析

这个题有些麻烦。

我的解法是使用 StackSet(保存处理过子节点,直接弹出,不再处理)。

还可以使用两个 Stack

甚至一个 Stack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 145. Binary Tree Postorder Traversal
 *
 * https://leetcode.com/problems/binary-tree-postorder-traversal/[Binary Tree Postorder Traversal - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-06-16 11:24
 */
public class _0145_BinaryTreePostorderTraversal {

  public List<Integer> postorderTraversal(TreeNode head) {
    if (Objects.isNull(head)) {
      return Collections.emptyList();
    }
    List<Integer> result = new LinkedList<>();
    Stack<TreeNode> s1 = new Stack<>();
    Stack<TreeNode> s2 = new Stack<>();
    s1.push(head);
    TreeNode c = null;
    while (!s1.empty()) {
      head = s1.pop();
      s2.push(head);
      if (Objects.nonNull(head.left)) {
        s1.push(head.left);
      }
      if (Objects.nonNull(head.right)) {
        s1.push(head.right);
      }
    }
    while (!s2.empty()) {
      result.add(s2.pop().val);
    }
    return result;
  }

  public List<Integer> postorderTraversal1(TreeNode root) {
    if (Objects.isNull(root)) {
      return Collections.emptyList();
    }
    List<Integer> result = new LinkedList<>();
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    Set<TreeNode> deal = new HashSet<>();
    while (!stack.empty()) {
      boolean updated = false;
      TreeNode node = stack.peek();
      if (!deal.contains(node)) {
        if (Objects.nonNull(node.right)) {
          stack.push(node.right);
          updated = true;
        }
        if (Objects.nonNull(node.left)) {
          stack.push(node.left);
          updated = true;
        }
        deal.add(node);
        if (updated) {
          continue;
        }
      }
      node = stack.pop();
      result.add(node.val);
    }
    return result;

  }

  public static void main(String[] args) {
    TreeNode tree = buildTree(Arrays.asList(1, null, 2, null, null, 3));
    _0145_BinaryTreePostorderTraversal solution = new _0145_BinaryTreePostorderTraversal();
    List<Integer> result = solution.postorderTraversal(tree);
    System.out.println(result);
  }
}

思考题

如何使用一个栈来解决这个问题?

146. LRU Cache

使用双向链表实现时,使用两个"空节点" headtail,可以有效减少空值判断,真是精巧。想起来上大学时,老师讲课提到这么一句。没想到竟然是如此实现。

LinkedHashMap 的实现也有不少的秘密可以探索。

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

The cache is initialized with a positive capacity.

Follow up:

Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 146. LRU Cache
 *
 * https://leetcode.com/problems/lru-cache/[LRU Cache - LeetCode]
 *
 * Design and implement a data structure for https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU[Least Recently Used (LRU) cache]. It should support the following operations: get and put.
 *
 * `get(key)` - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
 *
 * `put(key, value)` - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
 *
 * The cache is initialized with a *positive* capacity.
 *
 * *Follow up:*
 *
 * Could you do both operations in *O(1)* time complexity?
 *
 * .Example:
 * [source,java]
 * ----
 * LRUCache cache = new LRUCache(2);
 *
 * cache.put(1, 1);
 * cache.put(2, 2);
 * cache.get(1);       // returns 1
 * cache.put(3, 3);    // evicts key 2
 * cache.get(2);       // returns -1 (not found)
 * cache.put(4, 4);    // evicts key 1
 * cache.get(1);       // returns -1 (not found)
 * cache.get(3);       // returns 3
 * cache.get(4);       // returns 4
 * ----
 *
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 10:49
 */
public class _0146_LRUCache {
    /**
     * Runtime: 14 ms, faster than 90.57% of Java online submissions for LRU Cache.
     *
     * Memory Usage: 50.8 MB, less than 96.93% of Java online submissions for LRU Cache.
     *
     * Copy from: https://leetcode-cn.com/problems/lru-cache/solution/lru-huan-cun-ji-zhi-by-leetcode/[LRU 缓存机制 - LRU缓存机制 - 力扣(LeetCode)]
     */
    class LRUCache {
        private Map<Integer, DLinkedNode> data;
        private int capacity;
        private int size;
        private DLinkedNode head, tail;

        public LRUCache(int capacity) {
            this.size = 0;
            this.capacity = capacity;

            this.data = new HashMap<>();
            this.head = new DLinkedNode();
            this.tail = new DLinkedNode();

            this.head.next = this.tail;
            this.tail.prev = this.head;
        }

        public int get(int key) {
            DLinkedNode node = data.get(key);
            if (Objects.isNull(node)) {
                return -1;
            }
            moveToHead(node);
            return node.value;
        }

        public void put(int key, int value) {
            DLinkedNode node = data.get(key);
            if (Objects.isNull(node)) {
                DLinkedNode newNode = new DLinkedNode();
                newNode.key = key;
                newNode.value = value;
                data.put(key, newNode);
                addNode(newNode);
                ++size;
                if (size > capacity) {
                    DLinkedNode tail = popTail();
                    data.remove(tail.key);
                    --size;
                }
            } else {
                node.value = value;
                moveToHead(node);
            }
        }

        private void addNode(DLinkedNode node) {
            node.prev = head;
            node.next = head.next;

            head.next.prev = node;
            head.next = node;
        }

        private void removeNode(DLinkedNode node) {
            DLinkedNode prev = node.prev;
            DLinkedNode next = node.next;
            prev.next = next;
            next.prev = prev;
        }

        private void moveToHead(DLinkedNode node) {
            removeNode(node);
            addNode(node);
        }

        private DLinkedNode popTail() {
            DLinkedNode res = tail.prev;
            removeNode(res);
            return res;
        }

        private class DLinkedNode {
            int key;
            int value;
            DLinkedNode prev;
            DLinkedNode next;
        }
    }

    /**
     * Runtime: 22 ms, faster than 43.05% of Java online submissions for LRU Cache.
     *
     * Memory Usage: 58 MB, less than 51.53% of Java online submissions for LRU Cache.
     */
    class LRUCacheLinkedHashMap {
        private LinkedHashMap<Integer, Integer> data;

        public LRUCacheLinkedHashMap(int capacity) {
            data = new LinkedHashMap<Integer, Integer>(capacity, 0.75F, true) {
                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    return this.size() > capacity;
                }
            };
        }

        public int get(int key) {
            return data.getOrDefault(key, -1);
        }

        public void put(int key, int value) {
            data.put(key, value);
        }
    }

    private void test() {
        LRUCache solution = new LRUCache(2);
        solution.put(1, 1);
        solution.put(2, 2);
        int r1 = solution.get(1);
        System.out.println((r1 == 1) + " : " + r1);
        solution.put(3, 3);
        int r2 = solution.get(2);
        System.out.println((r2 == -1) + " : " + r2);
        solution.put(4, 4);
        int r3 = solution.get(1);
        System.out.println((r3 == -1) + " : " + r3);
        int r4 = solution.get(3);
        System.out.println((r4 == 3) + " : " + r4);
        int r5 = solution.get(4);
        System.out.println((r5 == 4) + " : " + r5);
    }

    public static void main(String[] args) {
        _0146_LRUCache solution = new _0146_LRUCache();
        solution.test();
    }
}

147. Insertion Sort List

Sort a linked list using insertion sort.

Insertion sort example 300px

[.small]#A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.

With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list#

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.

  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.

  3. It repeats until no input elements remain.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5
1
Unresolved directive in 0147-insertion-sort-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0147_InsertionSortList.java[]

148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 148. Sort List
 *
 * https://leetcode.com/problems/sort-list/[Sort List - LeetCode]
 *
 * Sort a linked list in O(n log n) time using constant space complexity.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 4->2->1->3
 * Output: 1->2->3->4
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input: -1->5->3->4->0
 * Output: -1->0->3->4->5
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-29 21:05
 */
public class _0148_SortList {

    /**
     * Runtime: 4 ms, faster than 62.99% of Java online submissions for Sort List.
     *
     * Memory Usage: 40.2 MB, less than 89.47% of Java online submissions for Sort List.
     */
    public ListNode sortList(ListNode head) {
        if (Objects.isNull(head) || Objects.isNull(head.next)) {
            return head;
        }
        ListNode prev = null;
        ListNode slow = head;
        ListNode fast = head;
        while (Objects.nonNull(fast) && Objects.nonNull(fast.next)) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        prev.next = null;

        ListNode firstResult = sortList(head);
        ListNode secondResult = sortList(slow);

        return merge(firstResult, secondResult);
    }

    private ListNode merge(ListNode first, ListNode second) {
        ListNode result = new ListNode(0);
        ListNode tail = result;
        while (Objects.nonNull(first) && Objects.nonNull(second)) {
            if (first.val < second.val) {
                tail.next = first;
                first = first.next;
            } else {
                tail.next = second;
                second = second.next;
            }
            tail = tail.next;
        }
        if (Objects.isNull(first)) {
            tail.next = second;
        }
        if (Objects.isNull(second)) {
            tail.next = first;
        }
        return result.next;
    }


    public static void main(String[] args) {
        _0148_SortList solution = new _0148_SortList();

        ListNode list1 = build(Arrays.asList(4, 2, 1, 3));
        printListNode(list1);
        ListNode re1 = solution.sortList(list1);
        printListNode(re1);
    }
}

149. Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o
+------------->
0  1  2  3  4

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1
Unresolved directive in 0149-max-points-on-a-line.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0149_MaxPointsOnALine.java[]

150. Evaluate Reverse Polish Notation

其实这只是一个栈操作。

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.

  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", ""]
*Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "", "-11", "*", "/", "*", "17", "", "5", "+"]
Output: 22
Explanation:
  10 * (6 / ((9 + 3) * -11) + 17) + 5
= 10 * (6 / (12 * -11) + 17) + 5
= 10 * (6 / -132 + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 150. Evaluate Reverse Polish Notation
 *
 * https://leetcode.com/problems/evaluate-reverse-polish-notation/[Evaluate Reverse Polish Notation - LeetCode]
 *
 * Evaluate the value of an arithmetic expression in https://en.wikipedia.org/wiki/Reverse_Polish_notation[Reverse Polish notation].
 *
 * Valid operators are `+`, `-`, `*`, `/`. Each operand may be an integer or another expression.
 *
 * *Note:*
 *
 * * Division between two integers should truncate toward zero.
 * * The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: ["2", "1", "+", "3", "*"]
 * Output: 9
 * Explanation: ((2 + 1) * 3) = 9
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: ["4", "13", "5", "/", "+"]
 * Output: 6
 * Explanation: (4 + (13 / 5)) = 6
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
 * Output: 22
 * Explanation:
 *   ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
 * = ((10 * (6 / (12 * -11))) + 17) + 5
 * = ((10 * (6 / -132)) + 17) + 5
 * = ((10 * 0) + 17) + 5
 * = (0 + 17) + 5
 * = 17 + 5
 * = 22
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 16:01
 */
public class _0150_EvaluateReversePolishNotation {
    /**
     * Runtime: 4 ms, faster than 97.32% of Java online submissions for Evaluate Reverse Polish Notation.
     *
     * Memory Usage: 41.1 MB, less than 6.00% of Java online submissions for Evaluate Reverse Polish Notation.
     */
    public int evalRPN(String[] tokens) {
        if (Objects.isNull(tokens) || tokens.length == 0) {
            return 0;
        }
        Deque<Integer> stack = new LinkedList<>();
        Set<String> operators = new HashSet<>(Arrays.asList("+", "-", "*", "/"));

        for (String token : tokens) {
            if (operators.contains(token)) {
                Integer v1 = stack.pop();
                Integer v2 = stack.pop();
                if ("+".equals(token)) {
                    stack.push(v1 + v2);
                    continue;
                }
                if ("-".equals(token)) {
                    stack.push(v2 - v1);
                    continue;
                }
                if ("*".equals(token)) {
                    stack.push(v1 * v2);
                    continue;
                }
                if ("/".equals(token)) {
                    stack.push(v2 / v1);
                    continue;
                }
            } else {
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }

    public static void main(String[] args) {
        _0150_EvaluateReversePolishNotation solution = new _0150_EvaluateReversePolishNotation();
        String[] t1 = {"2", "1", "+", "3", "*"};
        int r1 = solution.evalRPN(t1);
        System.out.println((r1 == 9) + " : " + r1);

        String[] t2 = {"4", "13", "5", "/", "+"};
        int r2 = solution.evalRPN(t2);
        System.out.println((r2 == 6) + " : " + r2);

        String[] t3 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        int r3 = solution.evalRPN(t3);
        System.out.println((r3 == 22) + " : " + r3);
    }
}

151. Reverse Words in a String

Given an input string, reverse the string word by word.

Example 1:

Input: “the sky is blue”
Output: “blue is sky the”

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Note:

  • A word is defined as a sequence of non-space characters.

  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.

  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Follow up:

For C programmers, try to solve it in-place in O(1) extra space.

1
Unresolved directive in 0151-reverse-words-in-a-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0151_ReverseWordsInAString.java[]

152. Maximum Product Subarray

这道题的阶梯思路跟另外某个题的解题思路很类似!

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.diguage.algorithm.leetcode;

/**
 * = 152. Maximum Product Subarray
 *
 * https://leetcode.com/problems/maximum-product-subarray/[Maximum Product Subarray - LeetCode]
 *
 * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [2,3,-2,4]
 * Output: 6
 * Explanation: [2,3] has the largest product 6.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [-2,0,-1]
 * Output: 0
 * Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 07:59
 */
public class _0152_MaximumProductSubarray {
    /**
     * Runtime: 1 ms, faster than 97.91% of Java online submissions for Maximum Product Subarray.
     *
     * Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Maximum Product Subarray.
     *
     * Copy form: https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity[Possibly simplest solution with O(n) time complexity - LeetCode Discuss]
     */
    public int maxProduct(int[] nums) {
        // store the result that is the max we have found so far
        int result = nums[0];
        // max/min stores the max/min product of
        // subarray that ends with the current number nums[i]
        for (int i = 1, max = result, min = result; i < nums.length; i++) {
            // multiplied by a negative makes big number smaller, small number bigger
            // so we redefine the extremums by swapping them
            if (nums[i] < 0) {
                int temp = max;
                max = min;
                min = temp;
            }
            // max/min product for the current number is either the current number itself
            // or the max/min by the previous number times the current one
            min = Math.min(nums[i], min * nums[i]);
            max = Math.max(nums[i], max * nums[i]);

            // the newly computed max value is a candidate for our global result
            result = Math.max(result, max);
        }
        return result;
    }

    public static void main(String[] args) {
        _0152_MaximumProductSubarray solution = new _0152_MaximumProductSubarray();
        int[] n1 = {2, 3, -2, 4};
        int r1 = solution.maxProduct(n1);
        System.out.println((r1 == 6) + " : " + r1);

        int[] n2 = {-2, 0, -1};
        int r2 = solution.maxProduct(n2);
        System.out.println((r2 == 0) + " : " + r1);
    }
}

153. Find Minimum in Rotated Sorted Array

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2]
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.diguage.algorithm.leetcode;

/**
 * = 153. Find Minimum in Rotated Sorted Array
 *
 * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/[Find Minimum in Rotated Sorted Array - LeetCode^]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-25 22:37
 */
public class _0153_FindMinimumInRotatedSortedArray {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array.
     * Memory Usage: 39.8 MB, less than 12.50% of Java online submissions for Find Minimum in Rotated Sorted Array.
     */
    public int findMin(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        int left = 0;
        int right = nums.length - 1;

        if (nums[left] < nums[right]) {
            return nums[left];
        }

        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;

            if (mid + 1 < nums.length && nums[mid] > nums[mid + 1]) {
                return nums[mid + 1];
            }

            if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) {
                return nums[mid];
            }

            if (nums[left] < nums[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        _0153_FindMinimumInRotatedSortedArray solution = new _0153_FindMinimumInRotatedSortedArray();
        int r1 = solution.findMin(new int[]{3, 4, 5, 1, 2});
        System.out.println(r1);
        int r2 = solution.findMin(new int[]{4, 5, 6, 7, 8, 9, 0, 1, 2});
        System.out.println(r2);
    }
}

解题分析

最省事的方式当然是遍历,但是,中等难度的题目不可能一个遍历就解决了。

针对有序数组,首先想到的就是二分查找。但是,这里的二分查找有需要做些特别处理。尤其注意的是,选出 mid 后,先去判断它或者它的邻居是否满足条件,满足就直接返回。然后再去调整范围。

154. Find Minimum in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

Find the minimum element.

The array may contain duplicates.

Example 1:

Input: [1,3,5]
Output: 1

Example 2:

Input: [2,2,2,0,1]
Output: 0

Note:

  • This is a follow up problem to <a href="https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/">Find Minimum in Rotated Sorted Array</a>.

  • Would allow duplicates affect the run-time complexity? How and why?

解题分析

这个算法的主结构跟二分查找是一样的:

  • 维护两个指针 lowhigh,使其代表查找范围的左边界和右边界。

  • 移动指针来缩小查找范围,通常将指针移动到 lowhigh 的中间(pivot = (low + high)/2)。这样查找范围就可以缩小一半,这也是二分查找名字的由来。

  • 在找到目标元素或者两个指针重合时(low == high),算法终止。

0154 axis

在传统的二分查找中,会将中轴元素(nums[pivot])与目标元素相比较。但在这个问题里面,需要将中轴元素与右边界元素(nums[high])相比较。

二分查找算法的难点在于如何更新左右边界指针。

  1. nums[pivot] < nums[high]

    0154 case 1

    中轴元素跟右边界元素在同一半边。这时候最小元素在中轴元素左边,将右边界指针移动到中轴元素位置(high = pivot)。

  2. nums[pivot] > nums[high]

    0154 case 2

    中轴元素跟右边界届元素在不同半边。这时候最小元素在中轴元素右边,将下届指针移动到中轴元素位置右边(low = pivot + 1)。

  3. nums[pivot] == nums[high]

    0154 case 3

    在这种情况下,不能确定最小元素在中轴元素的左边还是右边。

    为了缩小查找范围,安全的方法是将右边界指针减一(high = high - 1)。

    上述策略可以有效地避免死循环,同时可以保证永远不会跳过最小元素。

综上所述,这个算法跟二分查找有两处不同:

  • 这里我们将中轴元素与右边界元素相比较,传统的二分查找将中轴元素与目标元素相对比。

  • 当比较结果相同时,这里我们将左移右边界指针,而在传统的二分查找中直接返回结果。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.diguage.algorithm.leetcode;

/**
 * = 154. Find Minimum in Rotated Sorted Array II
 *
 * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/[Find Minimum in Rotated Sorted Array II - LeetCode^]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-25 23:32
 */
public class _0154_FindMinimumInRotatedSortedArrayII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array II.
     * Memory Usage: 39.5 MB, less than 31.25% of Java online submissions for Find Minimum in Rotated Sorted Array II.
     *
     * Copy from: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/solution/xun-zhao-xuan-zhuan-pai-xu-shu-zu-zhong-de-zui-1-8/[寻找旋转排序数组中的最小值 II - 寻找旋转排序数组中的最小值 II - 力扣(LeetCode)]
     */
    public int findMin(int[] nums) {
        int low = 0;
        int high = nums.length - 1;
        while (low < high) {
            int pivot = low + (high - low) / 2;
            if (nums[pivot] < nums[high]) {
                high = pivot;
            } else if (nums[pivot] > nums[high]) {
                low = pivot + 1;
            } else {
                high--;
            }
        }
        return nums[low];
    }

    public static void main(String[] args) {
        _0154_FindMinimumInRotatedSortedArrayII solution = new _0154_FindMinimumInRotatedSortedArrayII();
        int r3 = solution.findMin(new int[]{3, 1, 1});
        System.out.println(r3);

        int r1 = solution.findMin(new int[]{4, 5, 6, 7, 0, 1, 2});
        System.out.println(r1);

        int r2 = solution.findMin(new int[]{2, 2, 2, 2, 2, 2, 2, 2, 0, 1});
        System.out.println(r2);
    }
}

155. Min Stack

这道题解法还挺多。只使用一个栈的方案,还需要再思考思考。

TODO

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) — Push element x onto stack.

  • pop() — Removes the element on top of the stack.

  • top() — Get the top element.

  • getMin() — Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.diguage.algorithm.leetcode;

import java.util.Stack;

/**
 * = 155. Min Stack
 *
 * https://leetcode.com/problems/min-stack/[Min Stack - LeetCode]
 *
 * Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
 *
 * * push(x) -- Push element x onto stack.
 * * pop() -- Removes the element on top of the stack.
 * * top() -- Get the top element.
 * * getMin() -- Retrieve the minimum element in the stack.
 *
 *
 * .Example:
 * [source]
 * ----
 * MinStack minStack = new MinStack();
 * minStack.push(-2);
 * minStack.push(0);
 * minStack.push(-3);
 * minStack.getMin();   --> Returns -3.
 * minStack.pop();
 * minStack.top();      --> Returns 0.
 * minStack.getMin();   --> Returns -2.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 16:40
 */
class _0155_MinStack {

    // Runtime: 8 ms, faster than 18.94% of Java online submissions for Min Stack.
    // Memory Usage: 46.2 MB, less than 5.08% of Java online submissions for Min Stack.
    private Stack<Integer> stack;
    private Stack<Integer> helper;

    /**
     * initialize your data structure here.
     */
    public _0155_MinStack() {
        stack = new Stack<>();
        helper = new Stack<>();
    }

    public void push(int x) {
        stack.push(x);
        if (helper.isEmpty() || x < helper.peek()) {
            helper.push(x);
        } else {
            helper.push(helper.peek());
        }
    }

    public void pop() {
        stack.pop();
        helper.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return helper.peek();
    }

//    Runtime: 10 ms, faster than 14.80% of Java online submissions for Min Stack.
//    Memory Usage: 46.6 MB, less than 5.08% of Java online submissions for Min Stack.
//    private Stack<Integer> stack;
//    private PriorityQueue<Integer> queue;
//
//    /**
//     * initialize your data structure here.
//     */
//    public MinStack() {
//        stack = new Stack<>();
//        queue = new PriorityQueue<>();
//    }
//
//    public void push(int x) {
//        stack.push(x);
//        queue.add(x);
//    }
//
//    public void pop() {
//        Integer value = stack.pop();
//        queue.remove(value);
//    }
//
//    public int top() {
//        return stack.peek();
//    }
//
//    public int getMin() {
//        return queue.peek();
//    }

    public static void main(String[] args) {
        _0155_MinStack solution = new _0155_MinStack();
        solution.push(-2);
        solution.push(0);
        solution.push(-3);
        System.out.println(solution.getMin()); // -3
        solution.pop();
        System.out.println(solution.top()); // 0
        System.out.println(solution.getMin()); // -2
    }
}

156. Binary Tree Upside Down

1
Unresolved directive in 0156-binary-tree-upside-down.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0156_BinaryTreeUpsideDown.java[]

157. Read N Characters Given Read4

1
Unresolved directive in 0157-read-n-characters-given-read4.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0157_ReadNCharactersGivenRead4.java[]

158. Read N Characters Given Read4 II - Call multiple times

1
Unresolved directive in 0158-read-n-characters-given-read4-ii-call-multiple-times.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0158_ReadNCharactersGivenRead4IICallMultipleTimes.java[]

159. Longest Substring with At Most Two Distinct Characters

1
Unresolved directive in 0159-longest-substring-with-at-most-two-distinct-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0159_LongestSubstringWithAtMostTwoDistinctCharacters.java[]

160. Intersection of Two Linked Lists

0160 1
0160 2
0160 3

0 image::images/0160-4.png[]

没想到竟然可以将两个链表"相加"就可以得出正确结果:两个"相加",正好两个长度相等,最后部分就是重叠部分,双指针完美搞定!

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

160 statement

begin to intersect at node c1.

Example 1:

160 example 1
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

Example 2:

160 example 2
Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Reference of the node with value = 2
Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.

Example 3:

160 example 3
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.

Notes:

  • If the two linked lists have no intersection at all, return null.

  • The linked lists must retain their original structure after the function returns.

  • You may assume there are no cycles anywhere in the entire linked structure.

  • Your code should preferably run in O(n) time and use only O(1) memory.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;
import com.diguage.algorithm.util.ListNodeUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * = 160. Intersection of Two Linked Lists
 *
 * https://leetcode.com/problems/intersection-of-two-linked-lists/[Intersection of Two Linked Lists - LeetCode]
 *
 * Write a program to find the node at which the intersection of two singly linked lists begins.
 *
 * For example, the following two linked lists:
 *
 *
 * begin to intersect at node c1.
 *
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
 * Output: Reference of the node with value = 8
 * Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
 * Output: Reference of the node with value = 2
 * Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
 * Output: null
 * Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
 * Explanation: The two lists do not intersect, so return null.
 * ----
 *
 * *Notes:*
 *
 * If the two linked lists have no intersection at all, return `null`.
 * The linked lists must retain their original structure after the function returns.
 * You may assume there are no cycles anywhere in the entire linked structure.
 * Your code should preferably run in O(n) time and use only O(1) memory.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-12 11:12
 */
public class _0160_IntersectionOfTwoLinkedLists {
    /**
     * Runtime: 1 ms, faster than 99.29% of Java online submissions for Intersection of Two Linked Lists.
     *
     * Memory Usage: 43.3 MB, less than 5.71% of Java online submissions for Intersection of Two Linked Lists.
     *
     * Copy from: https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49785/Java-solution-without-knowing-the-difference-in-len![Java solution without knowing the difference in len! - LeetCode Discuss]
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (Objects.isNull(headA) || Objects.isNull(headB)) {
            return null;
        }
        ListNode a = headA;
        ListNode b = headB;
        while (a != b) {
            a = a == null ? headB : a.next;
            b = b == null ? headA : b.next;
        }
        return a;
    }

    /**
     * Runtime: 8 ms, faster than 14.19% of Java online submissions for Intersection of Two Linked Lists.
     * <p>
     * Memory Usage: 44.2 MB, less than 5.71% of Java online submissions for Intersection of Two Linked Lists.
     */
    public ListNode getIntersectionNodeSet(ListNode headA, ListNode headB) {
        if (Objects.isNull(headA) || Objects.isNull(headB)) {
            return null;
        }
        Set<ListNode> nodes = new HashSet<>();
        ListNode current = headA;
        while (Objects.nonNull(current)) {
            nodes.add(current);
            current = current.next;
        }
        current = headB;
        while (Objects.nonNull(current)) {
            if (nodes.contains(current)) {
                return current;
            }
            current = current.next;
        }
        return null;
    }

    public static void main(String[] args) {
        _0160_IntersectionOfTwoLinkedLists solution = new _0160_IntersectionOfTwoLinkedLists();
        ListNode l11 = ListNodeUtils.build(Arrays.asList(4, 1, 8, 4, 5));
        ListNode l12 = ListNodeUtils.build(Arrays.asList(5, 0, 1));
        l12.next.next.next = l11.next.next;
        ListNode r1 = solution.getIntersectionNode(l11, l12);
        ListNodeUtils.printListNode(r1);
    }
}

161. One Edit Distance

1
Unresolved directive in 0161-one-edit-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0161_OneEditDistance.java[]

162. Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = `[`1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
             or index number 5 where the peak element is 6.

Note:

Your solution should be in logarithmic complexity.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 162. Find Peak Element
 *
 * https://leetcode.com/problems/find-peak-element/[Find Peak Element - LeetCode]
 *
 * A peak element is an element that is greater than its neighbors.
 *
 * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
 *
 * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
 *
 * You may imagine that nums[-1] = nums[n] = -∞.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: nums = [1,2,3,1]
 * Output: 2
 * Explanation: 3 is a peak element and your function should return the index number 2.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [1,2,1,3,5,6,4]
 * Output: 1 or 5
 * Explanation: Your function can return either index number 1 where the peak element is 2,
 *              or index number 5 where the peak element is 6.
 * ----
 *
 * *Note:*
 *
 * Your solution should be in logarithmic complexity.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 11:03
 */
public class _0162_FindPeakElement {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Peak Element.
     *
     * Memory Usage: 38.4 MB, less than 100.00% of Java online submissions for Find Peak Element.
     *
     * Copy form: https://leetcode.com/problems/find-peak-element/solution/[Find Peak Element solution - LeetCode]
     */
    public int findPeakElement(int[] nums) {
        return search(nums, 0, nums.length - 1);
    }

    private int search(int[] nums, int low, int high) {
        if (low == high) {
            return low;
        }
        int mid = (low + high) / 2;
        if (nums[mid] < nums[mid + 1]) {
            return search(nums, mid + 1, high);
        }
        return search(nums, low, mid);
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Peak Element.
     *
     * Memory Usage: 38.8 MB, less than 100.00% of Java online submissions for Find Peak Element.
     */
    public int findPeakElementLinearScan(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return -1;
        }
        for (int i = 0; i < nums.length; i++) {
            if (isPeak(nums, i)) {
                return i;
            }
        }
        return -1;
    }

    private boolean isPeak(int[] nums, int index) {
        if (0 < index - 1 && nums[index - 1] > nums[index]) {
            return false;
        }
        if (index + 1 < nums.length && nums[index] < nums[index + 1]) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        _0162_FindPeakElement solution = new _0162_FindPeakElement();
        int[] a1 = {1, 2, 3, 1};
        int r1 = solution.findPeakElement(a1);
        System.out.println((r1 == 2) + " : " + r1);

        int[] a2 = {1, 2, 1, 3, 5, 6, 4};
        int r2 = solution.findPeakElement(a2);
        System.out.println((Arrays.asList(1, 5).contains(r2)) + " : " + r2);
    }
}

163. Missing Ranges

1
Unresolved directive in 0163-missing-ranges.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0163_MissingRanges.java[]

164. Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Return 0 if the array contains less than 2 elements.

Example 1:

Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
             (3,6) or (6,9) has the maximum difference 3.

Example 2:

Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

Note:

  • You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

  • Try to solve it in linear time/space.

1
Unresolved directive in 0164-maximum-gap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0164_MaximumGap.java[]

165. Compare Version Numbers

Compare two version numbers version1 and version2.

If version1 > version2 return 1; if version1 < version2 return -1;`otherwise return `0.

You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.

Example 1:

Input: version1 = "0.1", version2 = "1.1"
Output: -1

Example 2:

Input: version1 = "1.0.1", version2 = "1"
Output: 1

Example 3:

Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1

Example 4:

Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1”

Example 5:

Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0"

Note:

  1. Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes.

  2. Version strings do not start or end with dots, and they will not be two consecutive dots.

1
Unresolved directive in 0165-compare-version-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0165_CompareVersionNumbers.java[]

166. Fraction to Recurring Decimal

需要注意的是是:在 Map 中放的是被除数,而不是计算出来的位数digit。这样更方便处理!

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * = 166. Fraction to Recurring Decimal
 *
 * https://leetcode.com/problems/fraction-to-recurring-decimal/[Fraction to Recurring Decimal - LeetCode]
 *
 * Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
 *
 * If the fractional part is repeating, enclose the repeating part in parentheses.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: numerator = 1, denominator = 2
 * Output: "0.5"
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: numerator = 2, denominator = 1
 * Output: "2"
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: numerator = 2, denominator = 3
 * Output: "0.(6)"
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-11 13:14
 */
public class _0166_FractionToRecurringDecimal {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Fraction to Recurring Decimal.
     *
     * Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Fraction to Recurring Decimal.
     *
     * Copy from: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/51106/My-clean-Java-solution[My clean Java solution - LeetCode Discuss]
     */
    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        StringBuilder result = new StringBuilder();
        result.append(numerator > 0 ^ denominator > 0 ? "-" : "");
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        if (num > den) {
            result.append(num / den);
        } else {
            result.append("0");
        }
        num %= den;
        if (num == 0) {
            return result.toString();
        }
        result.append(".");
        Map<Long, Integer> numToIndexMap = new HashMap<>();
        // 这里需要注意,在 Map 中放的是被除数,而不是计算出来的位数digit。
        numToIndexMap.put(num, result.length());
        while (num != 0) {
            num *= 10;
            result.append(num / den);
            num %= den;
            if (numToIndexMap.containsKey(num)) {
                Integer index = numToIndexMap.get(num);
                result.insert(index, "(");
                result.append(")");
                break;
            } else {
                numToIndexMap.put(num, result.length());
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
        _0166_FractionToRecurringDecimal solultion = new _0166_FractionToRecurringDecimal();
        String r4 = solultion.fractionToDecimal(1, 333);
        System.out.println("0.(003)".equals(r4) + " : " + r4);

        String r3 = solultion.fractionToDecimal(2, 1);
        System.out.println("2".equals(r3) + " : " + r3);

        String r1 = solultion.fractionToDecimal(1, 2);
        System.out.println("0.5".equals(r1) + " : " + r1);

        String r2 = solultion.fractionToDecimal(-8, 7);
        System.out.println("-1.(142857)".equals(r2) + " : " + r2);
    }
}

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.

  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

解题思路

利用输入数组的有序性,可以从两边向中级"挤压"来查找正确解。

参考资料

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.

  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * = 167. Two Sum II - Input array is sorted
 *
 * https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/[Two Sum II - Input array is sorted - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-02-04 23:35
 */
public class _0167_TwoSumIIInputArrayIsSorted {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Two Sum II - Input array is sorted.
     * Memory Usage: 42.2 MB, less than 5.22% of Java online submissions for Two Sum II - Input array is sorted.
     *
     * Copy from: https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/solution/liang-shu-zhi-he-ii-shu-ru-you-xu-shu-zu-by-leetco/[两数之和 II - 输入有序数组 - 两数之和 II - 输入有序数组 - 力扣(LeetCode)]
     */
    public int[] twoSum(int[] numbers, int target) {
        int low = 0, high = numbers.length - 1;
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target) {
                return new int[]{low + 1, high + 1};
            } else if (sum < target) {
                low++;
            } else {
                high--;
            }
        }

        return new int[]{-1, -1};
    }

    /**
     * Runtime: 4 ms, faster than 14.69% of Java online submissions for Two Sum II - Input array is sorted.
     * Memory Usage: 41.8 MB, less than 5.22% of Java online submissions for Two Sum II - Input array is sorted.
     */
    public int[] twoSumPair(int[] numbers, int target) {
        Map<Integer, Pair> valueToIndexMap = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            valueToIndexMap.put(numbers[i], new Pair(numbers[i], i + 1));
        }
        for (int i = 0; i < numbers.length; i++) {
            int diff = target - numbers[i];
            if (valueToIndexMap.containsKey(diff)) {
                Pair pair = valueToIndexMap.get(diff);
                return new int[]{i + 1, pair.index};
            }
        }
        return null;
    }

    private class Pair {
        int value;
        int index;

        public Pair(int value, int index) {
            this.value = value;
            this.index = index;
        }
    }

    public static void main(String[] args) {
        _0167_TwoSumIIInputArrayIsSorted solution = new _0167_TwoSumIIInputArrayIsSorted();
        System.out.println(Arrays.toString(solution.twoSum(new int[]{2, 7, 11, 15}, 9)));
    }
}

168. Excel Sheet Column Title

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"
1
Unresolved directive in 0168-excel-sheet-column-title.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0168_ExcelSheetColumnTitle.java[]

169. Majority Element

Boyer-Moore Voting Algorithm 这个算法好巧妙啊!简直妙不可言!

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 169. Majority Element
 *
 * https://leetcode.com/problems/majority-element/[Majority Element - LeetCode]
 *
 * iven an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
 *
 * You may assume that the array is non-empty and the majority element always exist in the array.
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [3,2,3]
 * Output: 3
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [2,2,1,1,1,2,2]
 * Output: 2
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 12:33
 */
public class _0169_MajorityElement {
    /**
     *Runtime: 2 ms, faster than 61.24% of Java online submissions for Majority Element.
     *
     * Memory Usage: 42.4 MB, less than 59.56% of Java online submissions for Majority Element.
     *
     * Boyer-Moore Voting Algorithm
     *
     * Copy from: https://leetcode.com/problems/majority-element/solution/[Majority Element solution - LeetCode]
     */
    public int majorityElement(int[] nums) {
        int count = 0;
        Integer candidate = null;
        for (int num : nums) {
            if (0 == count) {
                candidate = num;
            }
            count += candidate == num ? +1 : -1;
        }
        return candidate;
    }

    /**
     * Runtime: 11 ms, faster than 45.56% of Java online submissions for Majority Element.
     *
     * Memory Usage: 40.6 MB, less than 99.26% of Java online submissions for Majority Element.
     */
    public int majorityElementMap(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        Map<Integer, Integer> numToCountMap = new HashMap<>();
        for (int num : nums) {
            Integer count = numToCountMap.getOrDefault(num, 0);
            numToCountMap.put(num, count + 1);
        }
        Map.Entry<Integer, Integer> result = null;
        for (Map.Entry<Integer, Integer> entry : numToCountMap.entrySet()) {
            if (result == null || result.getValue() < entry.getValue()) {
                result = entry;
            }
        }
        return result.getKey();
    }

    public static void main(String[] args) {
        _0169_MajorityElement solution = new _0169_MajorityElement();
        int[] a1 = {3, 2, 3};
        int r1 = solution.majorityElement(a1);
        System.out.println((r1 == 3) + " : " + r1);

        int[] a2 = {2, 2, 1, 1, 1, 2, 2};
        int r2 = solution.majorityElement(a2);
        System.out.println((r2 == 2) + " : " + r2);
    }
}

170. Two Sum III - Data structure design

1
Unresolved directive in 0170-two-sum-iii-data-structure-design.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0170_TwoSumIIIDataStructureDesign.java[]

171. Excel Sheet Column Number

目前的想法是从右向左计算,可以考虑一下,能否从左向右计算。可以参考: Here is my java solution - LeetCode Discuss

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28
    ...

Example 1:

Input: "A"
Output: 1

Example 2:

Input: "AB"
Output: 28

Example 3:

Input: "ZY"
Output: 701
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 171. Excel Sheet Column Number
 *
 * https://leetcode.com/problems/excel-sheet-column-number/[Excel Sheet Column Number - LeetCode]
 *
 * Given a column title as appear in an Excel sheet, return its corresponding column number.
 *
 * For example:
 *
 * ----
 *     A -> 1
 *     B -> 2
 *     C -> 3
 *     ...
 *     Z -> 26
 *     AA -> 27
 *     AB -> 28
 *     ...
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input: "A"
 * Output: 1
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: "AB"
 * Output: 28
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: "ZY"
 * Output: 701
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-14 00:12
 */
public class _0171_ExcelSheetColumnNumber {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Excel Sheet Column Number.
     *
     * Memory Usage: 36.1 MB, less than 100.00% of Java online submissions for Excel Sheet Column Number.
     */
    public int titleToNumber(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return 0;
        }
        char[] chars = s.toCharArray();
        int base = 1;
        int result = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            result += (chars[i] - 'A' + 1) * base;
            base *= 26;
        }
        return result;
    }

    public static void main(String[] args) {
        _0171_ExcelSheetColumnNumber solution = new _0171_ExcelSheetColumnNumber();
        int r1 = solution.titleToNumber("AA");
        System.out.println((r1 == 27) + " : " + r1);

        int r2 = solution.titleToNumber("ZY");
        System.out.println((r2 == 701) + " : " + r2);
    }
}

172. Factorial Trailing Zeroes

这个题的解题思路也很精巧,D瓜哥先来举例说明一下。

先来说明一下,产生零的因素:5(乘以2),1015………,即 5 的偶数倍。另外,显而易见,偶数比 5 的多很多,所以,我们只需要关注 5 的个数即可。D瓜哥用下面的序列来做进一步分析:

05,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130
 ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓  ↓   ↓   ↓   ↓   ↓   ↓   ↓   ↓
 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19, 20, 21, 22, 23, 24, 25, 26
             ↓              ↓              ↓               ↓                   ↓
             1,             2,             3,              4,                  5,
                                                                               ↓
                                                                               1,

为了方便说明,我把第一行做了处理,只关注 5x 的数,每个数都可以产生一个 0

将第一行的数除以 5,就得到了第二行的数字。这些数字中,一串 5x 的数,每个数又可以产生一个 0

以此类推,直到最后的序列只剩下不超过 5 截止。上面每行中的 5x 数字的个数就是我们需要的结果:结尾 0 的个数。

思路上,我受到了 这详尽的思路令我茅塞顿开!递归非递归都有哦! - LeetCode Discuss 的启发。但是,自认为比他的解释更容易理解。

Given an integer n, return the number of trailing zeroes in n!.

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

*Note: *Your solution should be in logarithmic time complexity.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.diguage.algorithm.leetcode;

/**
 * = 172. Factorial Trailing Zeroes
 *
 * https://leetcode.com/problems/factorial-trailing-zeroes/[Factorial Trailing Zeroes - LeetCode]
 *
 * Given an integer n, return the number of trailing zeroes in n!.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 3
 * Output: 0
 * Explanation: 3! = 6, no trailing zero.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 5
 * Output: 1
 * Explanation: 5! = 120, one trailing zero.
 * ----
 *
 * *Note:* Your solution should be in logarithmic time complexity.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-14 12:11
 */
public class _0172_FactorialTrailingZeroes {

    /**
     * Runtime: 1 ms, faster than 97.29% of Java online submissions for Factorial Trailing Zeroes.
     *
     * Memory Usage: 34 MB, less than 7.69% of Java online submissions for Factorial Trailing Zeroes.
     */
    public int trailingZeroes(int n) {
        int result = 0;
        while (n > 0) {
            result += n / 5;
            n /= 5;
        }
        return result;
    }

    public static void main(String[] args) {
        _0172_FactorialTrailingZeroes solultion = new _0172_FactorialTrailingZeroes();
        int r1 = solultion.trailingZeroes(5);
        System.out.println((r1 == 1) + " : " + r1);

        int r2 = solultion.trailingZeroes(100);
        System.out.println((r2 == 1) + " : " + r2);

        int r3 = solultion.trailingZeroes(30);
        System.out.println((r3 == 7) + " : " + r3);

        int r4 = solultion.trailingZeroes(200);
        System.out.println((r4 == 49) + " : " + r4);
    }
}

173. Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Example:

bst tree
BSTIterator iterator = new BSTIterator(root);
iterator.next();    // return 3
iterator.next();    // return 7
iterator.hasNext(); // return true
iterator.next();    // return 9
iterator.hasNext(); // return true
iterator.next();    // return 15
iterator.hasNext(); // return true
iterator.next();    // return 20
iterator.hasNext(); // return false

Note:

  • next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

  • You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.

1
Unresolved directive in 0173-binary-search-tree-iterator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0173_BinarySearchTreeIterator.java[]

174. Dungeon Game

<style type="text/css">table.dungeon, .dungeon th, .dungeon td { border:3px solid black; }

 .dungeon th, .dungeon td {
    text-align: center;
    height: 70px;
    width: 70px;
}
</style>
The demons had captured the princess (*P*) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (*K*) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT→ RIGHT → DOWN → DOWN.

<table class="dungeon"> <tbody> <tr> <td>-2 (K)</td> <td>-3</td> <td>3</td> </tr> <tr> <td>-5</td> <td>-10</td> <td>1</td> </tr> <tr> <td>10</td> <td>30</td> <td>-5 (P)</td> </tr> </tbody> </table>

Note:

  • The knight’s health has no upper bound.

  • Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

1
Unresolved directive in 0174-dungeon-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0174_DungeonGame.java[]

175. Combine Two Tables

Table: Person

----------------------+
| Column Name | Type    |
----------------------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
----------------------+
PersonId is the primary key column for this table.

Table: Address

----------------------+
| Column Name | Type    |
----------------------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
----------------------+
AddressId is the primary key column for this table.

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

FirstName, LastName, City, State
1
2
3
4
5
6
7
8
-- 175. Combine Two Tables
SELECT p.FirstName,
       p.LastName,
       a.City,
       a.State
FROM Person p
         LEFT JOIN Address a
                   ON p.PersonId = a.PersonId

176. Second Highest Salary

Write a SQL query to get the second highest salary from the Employee table.

------------+
| Id | Salary |
------------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
------------+

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

---------------------
| SecondHighestSalary |
---------------------
| 200                 |
---------------------
1
2
3
4
5
6
7
-- 176. Second Highest Salary
SELECT (
           SELECT DISTINCT Salary
           FROM Employee
           ORDER BY Salary DESC
           LIMIT 1 OFFSET 1
       ) AS SecondHighestSalary;

177. Nth Highest Salary

Write a SQL query to get the nth highest salary from the Employee table.

------------+
| Id | Salary |
------------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
------------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

------------------------
| getNthHighestSalary(2) |
------------------------
| 200                    |
------------------------
1
Unresolved directive in 0177-nth-highest-salary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0177_NthHighestSalary.java[]

178. Rank Scores

Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

-----------+
| Id | Score |
-----------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
-----------+

For example, given the above Scores table, your query should generate the following report (order by highest score):

-------------+
| Score | Rank |
-------------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
-------------+
1
Unresolved directive in 0178-rank-scores.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0178_RankScores.java[]

179. Largest Number

这道题很容易想到需要根据数字的字符串大小进行倒序排列(目的是将首个数字比较大的数字排在前面)。很容想到需要自定义 Comparator。最简单省事的方式就是直接将排序的两个字符串相加(左右,右左)进行比较就可以了。

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "`210"`

Example 2:

Input: [3,30,34,5,9]
Output: "`9534330"`

Note: The result may be very large, so you need to return a string instead of an integer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 179. Largest Number
 *
 * https://leetcode.com/problems/largest-number/[Largest Number - LeetCode]
 *
 * Given a list of non negative integers, arrange them such that they form the largest number.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [10,2]
 * Output: "210"
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [3,30,34,5,9]
 * Output: "9534330"
 * ----
 *
 * *Note:* The result may be very large, so you need to return a string instead of an integer.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 22:29
 */
public class _0179_LargestNumber {
    /**
     * Runtime: 21 ms, faster than 6.20% of Java online submissions for Largest Number.
     *
     * Memory Usage: 40.9 MB, less than 6.67% of Java online submissions for Largest Number.
     */
    public String largestNumber(int[] nums) {
        String[] strings = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            strings[i] = String.valueOf(nums[i]);
        }

        Arrays.sort(strings, (a, b) -> {
            String s1 = a + b;
            String s2 = b + a;
            return s2.compareTo(s1);
        });

        if ("0".equals(strings[0])) {
            return "0";
        }

        return String.join("", strings);
    }

    public static void main(String[] args) {
        _0179_LargestNumber solution = new _0179_LargestNumber();
        int[] n3 = {121, 12};
        String r3 = solution.largestNumber(n3);
        System.out.println("12121".equals(r3) + " : " + r3);

        int[] n1 = {10, 2};
        String r1 = solution.largestNumber(n1);
        System.out.println("210".equals(r1) + " : " + r1);

        int[] n2 = {3, 30, 34, 5, 9};
        String r2 = solution.largestNumber(n2);
        System.out.println("9534330".equals(r2) + " : " + r2);
    }
}

180. Consecutive Numbers

Write a SQL query to find all numbers that appear at least three times consecutively.

---------+
| Id | Num |
---------+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
---------+

For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.

-----------------
| ConsecutiveNums |
-----------------
| 1               |
-----------------
1
Unresolved directive in 0180-consecutive-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0180_ConsecutiveNumbers.java[]

181. Employees Earning More Than Their Managers

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

------------------------------+
| Id | Name  | Salary | ManagerId |
------------------------------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
------------------------------+

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

----------
| Employee |
----------
| Joe      |
----------
1
Unresolved directive in 0181-employees-earning-more-than-their-managers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0181_EmployeesEarningMoreThanTheirManagers.java[]

182. Duplicate Emails

Write a SQL query to find all duplicate emails in a table named Person.

-------------+
| Id | Email   |
-------------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
-------------+

For example, your query should return the following for the above table:

---------
| Email   |
---------
| a@b.com |
---------

Note: All emails are in lowercase.

1
Unresolved directive in 0182-duplicate-emails.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0182_DuplicateEmails.java[]

183. Customers Who Never Order

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

Table: Customers.

-----------+
| Id | Name  |
-----------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
-----------+

Table: Orders.

----------------+
| Id | CustomerId |
----------------+
| 1  | 3          |
| 2  | 1          |
----------------+

Using the above tables as example, return the following:

-----------
| Customers |
-----------
| Henry     |
| Max       |
-----------
1
Unresolved directive in 0183-customers-who-never-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0183_CustomersWhoNeverOrder.java[]

184. Department Highest Salary

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.

---------------------------------+
| Id | Name  | Salary | DepartmentId |
---------------------------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Jim   | 90000  | 1            |
| 3  | Henry | 80000  | 2            |
| 4  | Sam   | 60000  | 2            |
| 5  | Max   | 90000  | 1            |
---------------------------------+

The Department table holds all departments of the company.

--------------+
| Id | Name     |
--------------+
| 1  | IT       |
| 2  | Sales    |
--------------+

Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).

------------------------------
| Department | Employee | Salary |
------------------------------
| IT         | Max      | 90000  |
| IT         | Jim      | 90000  |
| Sales      | Henry    | 80000  |
------------------------------

Explanation:

Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.

1
Unresolved directive in 0184-department-highest-salary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0184_DepartmentHighestSalary.java[]

185. Department Top Three Salaries

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

---------------------------------+
| Id | Name  | Salary | DepartmentId |
---------------------------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
---------------------------------+

The Department table holds all departments of the company.

--------------+
| Id | Name     |
--------------+
| 1  | IT       |
| 2  | Sales    |
--------------+

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).

------------------------------
| Department | Employee | Salary |
------------------------------
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
------------------------------

Explanation:

In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.

1
Unresolved directive in 0185-department-top-three-salaries.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0185_DepartmentTopThreeSalaries.java[]

186. Reverse Words in a String II

1
Unresolved directive in 0186-reverse-words-in-a-string-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0186_ReverseWordsInAStringII.java[]

187. Repeated DNA Sequences

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.

Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.

Example:

Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"

Output: ["AAAAACCCCC", "CCCCCAAAAA"]
1
Unresolved directive in 0187-repeated-dna-sequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0187_RepeatedDNASequences.java[]

188. Best Time to Buy and Sell Stock IV

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 at most k transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
0188 1
public int maxProfit(int maxK, int[] prices) {
    if (Objects.isNull(prices) || prices.length == 0 || maxK == 0) {
        return 0;
    }
    if (maxK > prices.length / 2) { (1)
        return maxProfit(prices);
    }
    int[][][] dp = new int[prices.length][maxK + 1][2]; (2)
    for (int i = 0; i < prices.length; i++) {
        for (int k = maxK; k >= 1; k--) {
            if (i == 0) {
                dp[i][k][0] = 0;
                dp[i][k][1] = -prices[i]; (3)
                continue;
            }
            dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
            dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
        }
    }
    return dp[prices.length - 1][maxK][0];
}

public int maxProfit(int[] prices) {
    int dp0 = 0;
    int dp1 = Integer.MIN_VALUE;
    for (int i = 0; i < prices.length; i++) {
        int temp = dp0; (4)
        dp0 = Math.max(dp0, dp1 + prices[i]);
        dp1 = Math.max(dp1, temp - prices[i]);  (4)
    }
    return dp0;
}
1 为什么只需要大于 prices.length / 2 时就可以调用没有限制的函数?
2 为什么要把数组大小设置为 maxK + 1,而不是 maxK
3 为什么有时初始化成 -prices[i],而有时又是 Integer.MIN_VALUE
4 为什么有时需要保存这个变量?而有时又不需要?

思考题:再仔细思考思考这个解题框架。

参考资料

Say you have an array for which the i - th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 188. Best Time to Buy and Sell Stock IV
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/[Best Time to Buy and Sell Stock IV - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 20:54
 */
public class _0188_BestTimeToBuyAndSellStockIV {
    /**
     * Runtime: 11 ms, faster than 19.87% of Java online submissions for Best Time to Buy and Sell Stock IV.
     * Memory Usage: 40.9 MB, less than 13.89% of Java online submissions for Best Time to Buy and Sell Stock IV.
     *
     * Copy from https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
public int maxProfit(int maxK, int[] prices) {
    if (Objects.isNull(prices) || prices.length == 0 || maxK == 0) {
        return 0;
    }
    if (maxK > prices.length / 2) {
        return maxProfit(prices);
    }
    int[][][] dp = new int[prices.length][maxK + 1][2];
    for (int i = 0; i < prices.length; i++) {
        for (int k = maxK; k >= 1; k--) {
            if (i == 0) {
                dp[i][k][0] = 0;
                dp[i][k][1] = -prices[i];
                continue;
            }
            dp[i][k][0] = Math.max(dp[i - 1][k][0], dp[i - 1][k][1] + prices[i]);
            dp[i][k][1] = Math.max(dp[i - 1][k][1], dp[i - 1][k - 1][0] - prices[i]);
        }
    }
    return dp[prices.length - 1][maxK][0];
}

public int maxProfit(int[] prices) {
    int dp0 = 0;
    int dp1 = Integer.MIN_VALUE;
    for (int i = 0; i < prices.length; i++) {
        int temp = dp0;
        dp0 = Math.max(dp0, dp1 + prices[i]);
        dp1 = Math.max(dp1, temp - prices[i]);
    }
    return dp0;
}

    public static void main(String[] args) {
        _0188_BestTimeToBuyAndSellStockIV solution = new _0188_BestTimeToBuyAndSellStockIV();
        int[] p1 = {2, 4, 1};
        int r1 = solution.maxProfit(2, p1);
        System.out.println((r1 == 2) + " : " + r1);

        int[] p2 = {3, 2, 6, 5, 0, 3};
        int r2 = solution.maxProfit(2, p2);
        System.out.println((r2 == 7) + " : " + r2);
    }
}

189. Rotate Array

发现官网测试用例少了一个特殊情况:如果 k 大于两倍数组长度,提交的测试就会报错,但是官网却显示通过。

数组反转的方法也不错!反转时,直接使用界限的值进行加减比较简单省事!

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

  • Could you do it in-place with O(1) extra space?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 189. Rotate Array
 *
 * Given an array, rotate the array to the right by k steps, where k is non-negative.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [1,2,3,4,5,6,7] and k = 3
 * Output: [5,6,7,1,2,3,4]
 * Explanation:
 * rotate 1 steps to the right: [7,1,2,3,4,5,6]
 * rotate 2 steps to the right: [6,7,1,2,3,4,5]
 * rotate 3 steps to the right: [5,6,7,1,2,3,4]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [-1,-100,3,99] and k = 2
 * Output: [3,99,-1,-100]
 * Explanation:
 * rotate 1 steps to the right: [99,-1,-100,3]
 * rotate 2 steps to the right: [3,99,-1,-100]
 * ----
 *
 * *Note:*
 *
 * * Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
 * * Could you do it in-place with O(1) extra space?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 13:05
 */
public class _0189_RotateArray {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Array.
     *
     * Memory Usage: 37.4 MB, less than 100.00% of Java online submissions for Rotate Array.
     *
     * Copy from: https://leetcode.com/problems/rotate-array/solution/[Rotate Array solution - LeetCode]
     */
    public void rotate(int[] nums, int k) {
        if (Objects.isNull(nums) || nums.length == 0 || k % nums.length == 0) {
            return;
        }
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Rotate Array.
     * <p>
     * Memory Usage: 38 MB, less than 85.58% of Java online submissions for Rotate Array.
     */
    public void rotateExtraArray(int[] nums, int k) {
        if (Objects.isNull(nums) || nums.length == 0 ||  k % nums.length == 0) {
            return;
        }
        k %= nums.length;
        int[] temp = new int[k];
        for (int i = 0; i < k; i++) {
            temp[k - i - 1] = nums[nums.length - i - 1];
        }
        for (int i = nums.length - 1; i >= k; i--) {
            nums[i] = nums[i - k];
        }
        for (int i = 0; i < k; i++) {
            nums[i] = temp[i];
        }
    }

    public static void main(String[] args) {
        _0189_RotateArray solution = new _0189_RotateArray();
        int[] a1 = {1, 2, 3, 4, 5, 6, 7};
        int k1 = 3;
        solution.rotate(a1, k1);
        int[] r1 = {5, 6, 7, 1, 2, 3, 4};
        System.out.println(Arrays.equals(a1, r1) + " : " + Arrays.toString(a1));

        int[] a2 = {-1, -100, 3, 99};
        int k2 = 10;
        solution.rotate(a2, k2);
        int[] r2 = {3, 99, -1, -100};
        System.out.println(Arrays.equals(a2, r2) + " : " + Arrays.toString(a2));

        int[] a3 = {-1};
        int k3 = 2;
        solution.rotate(a3, k3);
        int[] r3 = {-1};
        System.out.println(Arrays.equals(a3, r3) + " : " + Arrays.toString(a3));

        int[] a4 = {1, 2};
        int k4 = 1;
        solution.rotate(a4, k4);
        int[] r4 = {2,1};
        System.out.println(Arrays.equals(a4, r4) + " : " + Arrays.toString(a4));
    }
}

190. Reverse Bits

没想到竟然可以用移位、相与和加法来解决!

Reverse bits of a given 32 bits unsigned integer.

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.

  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Follow up:

If this function is called many times, how would you optimize it?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.diguage.algorithm.leetcode;

/**
 * = 190. Reverse Bits
 *
 * https://leetcode.com/problems/reverse-bits/[Reverse Bits - LeetCode]
 *
 * Reverse bits of a given 32 bits unsigned integer.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 00000010100101000001111010011100
 * Output: 00111001011110000010100101000000
 * Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 11111111111111111111111111111101
 * Output: 10111111111111111111111111111111
 * Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
 * ----
 *
 * *Note:*
 *
 * * Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
 * * In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in *Example 2* above the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-15 22:55
 */
public class _0190_ReverseBits {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Bits.
     *
     * Memory Usage: 36.6 MB, less than 7.32% of Java online submissions for Reverse Bits.
     *
     * Copy from: https://leetcode.com/problems/reverse-bits/discuss/54746/Java-Solution-and-Optimization[Java Solution and Optimization - LeetCode Discuss]
     */
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result += n & 1;
            n >>>= 1;
            if (i < 31) {
                result <<= 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0190_ReverseBits solution = new _0190_ReverseBits();
        int r2 = solution.reverseBits(2);
        System.out.println((r2 == 964176192) + " : " + r2);

        int r1 = solution.reverseBits(43261596);
        System.out.println((r1 == 964176192) + " : " + r1);
    }
}

191. Number of 1 Bits

0191 1

减法解法让人开眼界。但是有一个疑问:它的效率就一定高吗?

Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.

  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3 above the input represents the signed integer -3.

Follow up:

If this function is called many times, how would you optimize it?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.diguage.algorithm.leetcode;

/**
 * = 191. Number of 1 Bits
 *
 * https://leetcode.com/problems/number-of-1-bits/[Number of 1 Bits - LeetCode]
 *
 * Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the https://en.wikipedia.org/wiki/Hamming_weight[Hamming weight]).
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 00000000000000000000000000001011
 * Output: 3
 * Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 00000000000000000000000010000000
 * Output: 1
 * Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 11111111111111111111111111111101
 * Output: 31
 * Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
 * ----
 *
 * *Note:*
 *
 * * Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
 * * In Java, the compiler represents the signed integers using https://en.wikipedia.org/wiki/Two%27s_complement[2's complement notation]. Therefore, in *Example 3* above the input represents the signed integer `-3`.
 *
 * *Follow up:*
 *
 * If this function is called many times, how would you optimize it?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 23:12
 */
public class _0191_NumberOf1Bits {
    /**
     * Runtime: 2 ms, faster than 7.49% of Java online submissions for Number of 1 Bits.
     *
     * Memory Usage: 38 MB, less than 5.41% of Java online submissions for Number of 1 Bits.
     */
    public int hammingWeight(int n) {
        int result = 0;
        while (n != 0) {
            if ((n & 1) == 1) {
                ++result;
            }
            n = n >>> 1;
        }
        return result;
    }

    /**
     * Runtime: 2 ms, faster than 7.49% of Java online submissions for Number of 1 Bits.
     *
     * Memory Usage: 38.2 MB, less than 5.41% of Java online submissions for Number of 1 Bits.
     *
     * Copy from: https://leetcode.com/problems/number-of-1-bits/solution/[Number of 1 Bits solution - LeetCode]
     */
    public int hammingWeightSubtraction(int n) {
        int result = 0;
        while (n != 0) {
            result++;
            n &= (n - 1);
        }
        return result;
    }

    public static void main(String[] args) {
        _0191_NumberOf1Bits solution = new _0191_NumberOf1Bits();
        int r1 = solution.hammingWeight(-3);
        System.out.println((r1 == 31) + " : " + r1);
    }
}

192. Word Frequency

Write a bash script to calculate the frequency of each word in a text file words.txt.

For simplicity sake, you may assume:

  • words.txt contains only lowercase characters and space ' ' characters.

  • Each word must consist of lowercase characters only.

  • Words are separated by one or more whitespace characters.

Example:

Assume that words.txt has the following content:

the day is sunny the the
the sunny is is

Your script should output the following, sorted by descending frequency:

the 4
is 3
sunny 2
day 1

Note:

  • Don’t worry about handling ties, it is guaranteed that each word’s frequency count is unique.

  • Could you write it in one-line using <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html">Unix pipes</a>?

1
Unresolved directive in 0192-word-frequency.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0192_WordFrequency.java[]

193. Valid Phone Numbers

Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.

You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)

You may also assume each line in the text file must not contain leading or trailing white spaces.

Example:

Assume that file.txt has the following content:

987-123-4567
123 456 7890
(123) 456-7890

Your script should output the following valid phone numbers:

987-123-4567
(123) 456-7890
1
Unresolved directive in 0193-valid-phone-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0193_ValidPhoneNumbers.java[]

194. Transpose File

Given a text file file.txt, transpose its content.

You may assume that each row has the same number of columns and each field is separated by the ' ' character.

Example:

If file.txt has the following content:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30
1
Unresolved directive in 0194-transpose-file.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0194_TransposeFile.java[]

195. Tenth Line

Given a text file file.txt, print just the 10th line of the file.

Example:

Assume that file.txt has the following content:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

Your script should output the tenth line, which is:

Line 10

<div class="spoilers">*Note:*

  1. If the file contains less than 10 lines, what should you output?

  2. There’s at least three different solutions. Try to explore all possibilities.

1
Unresolved directive in 0195-tenth-line.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0195_TenthLine.java[]

196. Delete Duplicate Emails

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

----------------------+
| Id | Email            |
----------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
----------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

----------------------+
| Id | Email            |
----------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
----------------------+

Note:

Your output is the whole Person table after executing your sql. Use delete statement.

1
Unresolved directive in 0196-delete-duplicate-emails.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0196_DeleteDuplicateEmails.java[]

197. Rising Temperature

Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday’s) dates.

---------------------------------------------
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
---------------------------------------------
|       1 |       2015-01-01 |               10 |
|       2 |       2015-01-02 |               25 |
|       3 |       2015-01-03 |               20 |
|       4 |       2015-01-04 |               30 |
---------------------------------------------

For example, return the following Ids for the above Weather table:

----
| Id |
----
|  2 |
|  4 |
----
1
Unresolved directive in 0197-rising-temperature.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0197_RisingTemperature.java[]

198. House Robber

假设 f(k) = 从前 k 个房屋中能抢劫到的最大数额,Ai = 第 i 个房屋的钱数。

当 n=1 时,显然 f(1) = A1

当 n=2 时,f(2) = max(A1, A2)。

当 n=3 时,有两种选项:

  1. 将第三个房间金额和第一个房间金额相加;

  2. 不算第三个房间,保持当前最大金额。

于是,可以总结出公式: \(f(k)=\max \left(f(k-2)+A_{k}, f(k-1)\right)\)。

剩下的工作就好办了。

让 D瓜哥 使用 动态规划的模式 来重新解读一下:

  1. 刻画一个最优解的结构特征:求解抢劫金额最大值。

  2. 递归地定义最优解的值: \(f(k)=\max \left(f(k-2)+A_{k}, f(k-1)\right)\)。

  3. 计算最优解的值,通常采用自底向上的方法:D瓜哥也按照动态规划(注意表格)的方式来实现,采用自底向上+备忘录的方式来求解,创建一个长度为 n+1 的数组,第 i 个元素表示到第 i 个房间为止,最大抢劫金额;则第 0 个元素为 0,第 1 个元素为 A1。然后根据上述公式定义,以此类推……

  4. 利用计算出的信息构造一个最优解。这一步不需要,暂时忽略。

使用递归、递归+备忘录、自底向上+备忘录,自底向上+简化备忘录四种方式分别实现。

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 198. House Robber
 *
 * https://leetcode.com/problems/house-robber/[House Robber - LeetCode]
 *
 * You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and *it will automatically contact the police if two adjacent houses were broken into on the same night.*
 *
 * Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight *without alerting the police.*
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,2,3,1]
 * Output: 4
 * Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
 *              Total amount you can rob = 1 + 3 = 4.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [2,7,9,3,1]
 * Output: 12
 * Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
 *              Total amount you can rob = 2 + 9 + 1 = 12.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-23 22:37
 */
public class _0198_HouseRobber {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for House Robber.
     *
     * Memory Usage: 41.2 MB, less than 5.26% of Java online submissions for House Robber.
     */
    public int rob(int[] nums) {
        int k2 = 0;
        int k1 = 0;
        for (int num : nums) {
            int current = Math.max(k2 + num, k1);
            k2 = k1;
            k1 = current;
        }
        return k1;
    }

    /**
     * Runtime: 1 ms, faster than 5.81% of Java online submissions for House Robber.
     *
     * Memory Usage: 41.9 MB, less than 5.26% of Java online submissions for House Robber.
     */
    public int robDP(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int[] memo = new int[nums.length + 1];
        memo[0] = 0;
        memo[1] = nums[0];
        for (int i = 2; i < memo.length; i++) {
            int max = Math.max(memo[i - 2] + nums[i - 1], memo[i - 1]);
            memo[i] = max;
        }
        return memo[nums.length];
    }

    /**
     * Runtime: 1 ms, faster than 5.81% of Java online submissions for House Robber.
     *
     * Memory Usage: 41.3 MB, less than 5.26% of Java online submissions for House Robber.
     */
    public int robRecursionWithMemo(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int[] memo = new int[nums.length];
        Arrays.fill(memo, Integer.MIN_VALUE);
        memo[0] = nums[0];
        rob(nums, memo, nums.length - 1);
        return memo[nums.length - 1];
    }

    private int rob(int[] nums, int[] memo, int k) {
        if (k == -2 || k == -1) {
            return 0;
        }

        int rob2 = 0;
        if (k - 2 >= 0 && memo[k - 2] >= 0) {
            rob2 = memo[k - 2];
        } else {
            rob2 = rob(nums, memo, k - 2);
        }
        int rob1 = 0;
        if (k - 1 >= 0 && memo[k - 1] >= 0) {
            rob1 = memo[k - 1];
        } else {
            rob1 = rob(nums, memo, k - 1);
        }
        int rob0 = Math.max(rob2 + nums[k], rob1);
        memo[k] = rob0;
        return rob0;
    }


    // -----
    public int robRecursion(int[] nums) {
        return rob(nums, nums.length - 1);
    }

    private int rob(int[] nums, int k) {
        if (k == -2 || k == -1) {
            return 0;
        }
        return Math.max(rob(nums, k - 2) + nums[k], rob(nums, k - 1));
    }

    public static void main(String[] args) {
        _0198_HouseRobber solution = new _0198_HouseRobber();
        int[] n1 = {1, 2, 3, 1};
        int r1 = solution.rob(n1);
        System.out.println((r1 == 4) + " : " + r1);

        int[] n2 = {2, 7, 9, 3, 1};
        int r2 = solution.rob(n2);
        System.out.println((r2 == 12) + " : " + r2);
    }
}

199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
1
Unresolved directive in 0199-binary-tree-right-side-view.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0199_BinaryTreeRightSideView.java[]

200. Number of Islands

思考题:看题解可以使用 UnionFind 来解决这个问题。可以思考一下,如何实现?

这道题与 0130-surrounded-regions.adoc 类似。

Given a 2d grid map of ’1'`s (land) and ’0'`s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example 1:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 200. Number of Islands
 *
 * Given a 2d grid map of `'1'`s (land) and `'0'`s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
 *
 * .Example 1:
 * [source]
 * ----
 * Input:
 * 11110
 * 11010
 * 11000
 * 00000
 *
 * Output: 1
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input:
 * 11000
 * 11000
 * 00100
 * 00011
 *
 * Output: 3
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 23:42
 */
public class _0200_NumberOfIslands {
    /**
     * Runtime: 1 ms, faster than 99.99% of Java online submissions for Number of Islands.
     *
     * Memory Usage: 42 MB, less than 41.86% of Java online submissions for Number of Islands.
     *
     * Copy from: https://leetcode-cn.com/problems/number-of-islands/solution/dao-yu-shu-liang-by-leetcode/[岛屿数量 - 岛屿数量 - 力扣(LeetCode)]
     */
    public int numIslands(char[][] grid) {
        if (Objects.isNull(grid) || grid.length == 0) {
            return 0;
        }
        int yLength = grid.length;
        int xLength = grid[0].length;
        int result = 0;
        for (int y = 0; y < yLength; y++) {
            for (int x = 0; x < xLength; x++) {
                if (grid[y][x] == '1') {
                    result++;
                    dfs(grid, y, x);
                }
            }
        }

        return result;
    }

    private void dfs(char[][] grid, int y, int x) {
        int yLength = grid.length;
        int xLength = grid[0].length;
        if (y < 0 || y >= yLength || x < 0 || x >= xLength
                || grid[y][x] == '0') {
            return;
        }
        grid[y][x] = '0';
        dfs(grid, y - 1, x);
        dfs(grid, y + 1, x);
        dfs(grid, y, x - 1);
        dfs(grid, y, x + 1);
    }

    public static void main(String[] args) {
        _0200_NumberOfIslands solution = new _0200_NumberOfIslands();
        char[][] g1 = {
                {'1', '1', '0', '0', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '1', '0', '0'},
                {'0', '0', '0', '1', '1'}
        };
        int r1 = solution.numIslands(g1);
        System.out.println((r1 == 3) + " : " + r1);
    }
}

201. Bitwise AND of Numbers Range

Given a range [m, n] where 0 ⇐ m ⇐ n ⇐ 2147483647, return the bitwise AND of all numbers in this range, inclusive.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0
1
Unresolved directive in 0201-bitwise-and-of-numbers-range.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0201_BitwiseANDOfNumbersRange.java[]

202. Happy Number

竟然可以使用"双指针",类似判断链表中是否有环的思路!妙!

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

*Example: *

Input: 19
Output: true
Explanation:
1^2^ + 9^2^ = 82
8^2^ + 2^2^ = 68
6^2^ + 8^2^ = 100
1^2^ + 0^2^ + 0^2^ = 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.diguage.algorithm.leetcode;

/**
 * = 202. Happy Number
 *
 * https://leetcode.com/problems/happy-number/[Happy Number - LeetCode]
 *
 * Write an algorithm to determine if a number is "happy".
 *
 * A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
 *
 * .Example:
 * [source]
 * ----
 * Input: 19
 * Output: true
 * Explanation:
 * 12 + 92 = 82
 * 82 + 22 = 68
 * 62 + 82 = 100
 * 12 + 02 + 02 = 1
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-10 21:40
 */
public class _0202_HappyNumber {
    /**
     * Runtime: 1 ms, faster than 99.99% of Java online submissions for Happy Number.
     *
     * Memory Usage: 33.4 MB, less than 10.60% of Java online submissions for Happy Number.
     *
     * Copy from: https://leetcode.com/problems/happy-number/discuss/56917/My-solution-in-C(-O(1)-space-and-no-magic-math-property-involved-)[My solution in C( O(1) space and no magic math property involved ) - LeetCode Discuss]
     */
    public boolean isHappy(int n) {
        int slow = n;
        int fast = n;
        do {
            slow = digitSquareSum(slow);
            fast = digitSquareSum(fast);
            fast = digitSquareSum(fast);
            if (fast == 1) {
                return true;
            }
        } while (slow != fast);
        return false;
    }

    public int digitSquareSum(int n) {
        int sum = 0;
        while (n != 0) {
            int temp = n % 10;
            sum += temp * temp;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        _0202_HappyNumber solution = new _0202_HappyNumber();
        boolean happy = solution.isHappy(19);
        System.out.println(happy);
    }
}

203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
1
Unresolved directive in 0203-remove-linked-list-elements.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0203_RemoveLinkedListElements.java[]

204. Count Primes

如何实现一个高效的筛选法?

Count the number of prime numbers less than a non-negative number, n.

Example:

Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.diguage.algorithm.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * = 204. Count Primes
 *
 * https://leetcode.com/problems/count-primes/[Count Primes - LeetCode]
 *
 * ount the number of prime numbers less than a non-negative number, **n**.
 *
 * .Example:
 * [source]
 * ----
 * Input: 10
 * Output: 4
 * Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-10 23:04
 */
public class _0204_CountPrimes {
    /**
     * Runtime: 163 ms, faster than 25.96% of Java online submissions for Count Primes.
     *
     * Memory Usage: 93.7 MB, less than 5.66% of Java online submissions for Count Primes.
     */
    public int countPrimes(int n) {
        if (n < 3) {
            return 0;
        }
        Set<Integer> numbers = new HashSet<>();
        numbers.add(2);
        for (int i = 3; i < n; ) {
            numbers.add(i);
            i += 2;
        }
        for (int i = 3; i < Math.sqrt(n); ) {
            for (int j = 3; i * j < n; ) {
                numbers.remove(i * j);
                j += 2;
            }
            i += 2;
        }
        return numbers.size();
    }

    public static void main(String[] args) {
        _0204_CountPrimes solution = new _0204_CountPrimes();
        int r1 = solution.countPrimes(100);
        System.out.println((r1 == 4) + " : " + r1);
    }
}

205. Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:

You may assume both *_s _*and *_t _*have the same length.

1
Unresolved directive in 0205-isomorphic-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0205_IsomorphicStrings.java[]

206. Reverse Linked List

递归需要加强一下,反转链表的递归细节再推敲推敲。

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 206. Reverse Linked List
 *
 * https://leetcode.com/problems/reverse-linked-list/[Reverse Linked List - LeetCode]
 *
 * Reverse a singly linked list.
 *
 * .Example:
 * [source]
 * ----
 * Input: 1->2->3->4->5->NULL
 * Output: 5->4->3->2->1->NULL
 * ----
 *
 * *Follow up:*
 *
 * A linked list can be reversed either iteratively or recursively. Could you implement both?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-12 12:47
 */
public class _0206_ReverseLinkedList {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List.
     *
     * Memory Usage: 38 MB, less than 6.48% of Java online submissions for Reverse Linked List.
     */
    public ListNode reverseList(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        ListNode result = null;
        ListNode current = head;
        while (Objects.nonNull(current)) {
            ListNode pre = current.next;
            current.next = result;
            result = current;
            current = pre;
        }
        return result;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List.
     *
     * Memory Usage: 37.8 MB, less than 51.44% of Java online submissions for Reverse Linked List.
     */
    public ListNode reverseListRecursion(ListNode head) {
        if (Objects.isNull(head) || Objects.isNull(head.next)) {
            return head;
        }
        // 这个反转地方,还要再仔细推敲一下!!
        ListNode node = reverseListRecursion(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

    public static void main(String[] args) {
        _0206_ReverseLinkedList solution = new _0206_ReverseLinkedList();
        ListNode r1 = solution.reverseList(build(Arrays.asList(1, 2, 3, 4, 5)));
        printListNode(r1);
    }
}

207. Course Schedule

TODO: 研究一下图相关算法和拓扑排序。

拓扑排序通常用来“排序”具有依赖关系的任务。

拓扑排序出来的结果是应该不是有序(升序或降序)。只是一个前后顺序。

思考题:参考资料中提到,表示图可以使用"邻接矩阵"和"邻接表"。尝试使用邻接表来重新实现。

参考资料

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
             To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
             To take course 1 you should have finished course 0, and to take course 0 you should
             also have finished course 1. So it is impossible.

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

  2. You may assume that there are no duplicate edges in the input prerequisites.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.diguage.algorithm.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * = 207. Course Schedule
 *
 * https://leetcode.com/problems/course-schedule/[Course Schedule - LeetCode]
 *
 * There are a total of n courses you have to take, labeled from `0` to `n-1`.
 *
 * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: `[0,1]`
 *
 * Given the total number of courses and a list of prerequisite *pairs*, is it possible for you to finish all courses?
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 2, [[1,0]]
 * Output: true
 * Explanation: There are a total of 2 courses to take.
 *              To take course 1 you should have finished course 0. So it is possible.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 2, [[1,0],[0,1]]
 * Output: false
 * Explanation: There are a total of 2 courses to take.
 *              To take course 1 you should have finished course 0, and to take course 0 you should
 *              also have finished course 1. So it is impossible.
 * ----
 *
 * *Note:*
 *
 * * The input prerequisites is a graph represented by *a list of edges*, not adjacency matrices. Read more about https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs[how a graph is represented].
 * * You may assume that there are no duplicate edges in the input prerequisites.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 16:36
 */
public class _0207_CourseSchedule {
    /**
     * Runtime: 20 ms, faster than 36.81% of Java online submissions for Course Schedule.
     *
     * Memory Usage: 74.1 MB, less than 5.39% of Java online submissions for Course Schedule.
     *
     * Copy from: https://leetcode.com/problems/course-schedule/discuss/58516/Easy-BFS-Topological-sort-Java[Easy BFS Topological sort, Java - LeetCode Discuss]
     */
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[][] matrix = new int[numCourses][numCourses];
        int[] indegree = new int[numCourses];
        for (int[] prere : prerequisites) {
            int latter = prere[0];
            int formmer = prere[1];
            matrix[formmer][latter]++;
            indegree[latter]++;
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (indegree[i] == 0) {
                queue.offer(i);
            }
        }
        int count = 0;
        while (!queue.isEmpty()) {
            Integer course = queue.poll();
            count++;
            for (int i = 0; i < numCourses; i++) {
                if (matrix[course][i] != 0) {
                    if (--indegree[i] == 0) {
                        queue.offer(i);
                    }
                }
            }
        }
        return count == numCourses;
    }

    public static void main(String[] args) {
        _0207_CourseSchedule solution = new _0207_CourseSchedule();
        int[][] p1 = {{1, 0}};
        boolean r1 = solution.canFinish(2, p1);
        System.out.println(r1);

        int[][] p2 = {{1, 0}, {0, 1}};
        boolean r2 = solution.canFinish(2, p2);
        System.out.println(!r2);
    }
}

208. Implement Trie (Prefix Tree)

没想到 Trie Tree 实现起来一点也不复杂!

思考题:如何实现一个工业级的 Trie Tree?

0208 1

参考资料

Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.

  • All inputs are guaranteed to be non-empty strings.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 208. Implement Trie (Prefix Tree)
 *
 * https://leetcode.com/problems/implement-trie-prefix-tree/[Implement Trie (Prefix Tree) - LeetCode]
 *
 * Implement a trie with `insert`, `search`, and `startsWith` methods.
 *
 * .Example:
 * [source,java]
 * ----
 * Trie trie = new Trie();
 *
 * trie.insert("apple");
 * trie.search("apple");   // returns true
 * trie.search("app");     // returns false
 * trie.startsWith("app"); // returns true
 * trie.insert("app");
 * trie.search("app");     // returns true
 * ----
 *
 * *Note:*
 *
 * * You may assume that all inputs are consist of lowercase letters `a-z`.
 * * All inputs are guaranteed to be non-empty strings.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 19:47
 */
public class _0208_ImplementTriePrefixTree {
    /**
     * Runtime: 69 ms, faster than 11.59% of Java online submissions for Implement Trie (Prefix Tree).
     *
     * Memory Usage: 62.6 MB, less than 5.77% of Java online submissions for Implement Trie (Prefix Tree).
     */
    class Trie {
        private int ALPHABET_SIZE = 26;

        class TrieNode {
            private TrieNode[] alphabet;
            private boolean isEnd;

            public TrieNode() {
                this.alphabet = new TrieNode[ALPHABET_SIZE];
                Arrays.fill(this.alphabet, null);
                this.isEnd = false;
            }
        }

        private TrieNode[] root;

        /**
         * Initialize your data structure here.
         */
        public Trie() {
            this.root = new TrieNode[ALPHABET_SIZE];
            Arrays.fill(this.root, null);
        }

        /**
         * Inserts a word into the trie.
         */
        public void insert(String word) {
            char[] chars = word.toCharArray();
            TrieNode[] current = this.root;
            for (int i = 0; i < chars.length; i++) {
                int index = chars[i] - 'a';
                if (Objects.isNull(current[index])) {
                    current[index] = new TrieNode();
                }
                if (i == chars.length - 1) {
                    current[index].isEnd = true;
                }
                current = current[index].alphabet;
            }
        }

        /**
         * Returns if the word is in the trie.
         */
        public boolean search(String word) {
            char[] chars = word.toCharArray();
            TrieNode[] current = this.root;
            for (int i = 0; i < chars.length; i++) {
                int index = chars[i] - 'a';
                if (Objects.isNull(current[index])) {
                    return false;
                }
                if (i == chars.length - 1) {
                    return current[index].isEnd;
                }
                current = current[index].alphabet;
            }
            return false;
        }

        /**
         * Returns if there is any word in the trie that starts with the given prefix.
         */
        public boolean startsWith(String prefix) {
            char[] chars = prefix.toCharArray();
            TrieNode[] current = this.root;
            for (int i = 0; i < chars.length; i++) {
                int index = chars[i] - 'a';
                if (Objects.isNull(current[index])) {
                    return false;
                }
                current = current[index].alphabet;
            }
            return true;
        }
    }

    private void test() {
        Trie trie = new Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));
        System.out.println(!trie.search("app"));
        System.out.println(trie.startsWith("app"));
        trie.insert("app");
        System.out.println(trie.search("app"));
    }

    public static void main(String[] args) {
        _0208_ImplementTriePrefixTree solution = new _0208_ImplementTriePrefixTree();
        solution.test();
    }
}

209. Minimum Size Subarray Sum

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

*Example: *

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.

<div class="spoilers">*Follow up:*

<div class="spoilers">If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

1
Unresolved directive in 0209-minimum-size-subarray-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0209_MinimumSizeSubarraySum.java[]

210. Course Schedule II

思考题:看题解,可以通过深度优先遍历来实现。思考如何实现?

0210 1
0210 2

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

Example 1:

Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
             course 0. So the correct course order is [0,1] .

Example 2:

Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both
             courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
             So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

  2. You may assume that there are no duplicate edges in the input prerequisites.

1
Unresolved directive in 0210-course-schedule-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0210_CourseScheduleII.java[]

211. Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:

You may assume that all words are consist of lowercase letters a-z.

1
Unresolved directive in 0211-add-and-search-word-data-structure-design.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0211_AddAndSearchWordDataStructureDesign.java[]

212. Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board.

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Example:

Input:
board = [
  ['o','a','a','n'],
  ['e','t','a',' e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]
words = ["oath","pea","eat","rain"]

Output: ["eat","oath"]

Note:

  1. All inputs are consist of lowercase letters a-z.

  2. The values of words are distinct.

1
Unresolved directive in 0212-word-search-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0212_WordSearchII.java[]

213. House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.
1
Unresolved directive in 0213-house-robber-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0213_HouseRobberII.java[]

214. Shortest Palindrome

Given a string *s*, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"
1
Unresolved directive in 0214-shortest-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0214_ShortestPalindrome.java[]

215. Kth Largest Element in an Array

没想到竟然可以使用快排的套路来解决这个问题。

0215 1

参考资料

Find the *k*th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

*Note: *

You may assume k is always valid, 1 ≤ k ≤ array’s length.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;

/**
 * = 215. Kth Largest Element in an Array
 *
 * https://leetcode.com/problems/kth-largest-element-in-an-array/[Kth Largest Element in an Array - LeetCode]
 *
 * Find the **k**th largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [3,2,1,5,6,4] and k = 2
 * Output: 5
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [3,2,3,1,2,4,5,5,6] and k = 4
 * Output: 4
 * ----
 *
 * *Note:*
 *
 * You may assume k is always valid, 1 ≤ k ≤ array's length.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 18:00
 */
public class _0215_KthLargestElementInAnArray {
    private int[] nums;

    private void swap(int a, int b) {
        int temp = this.nums[a];
        this.nums[a] = this.nums[b];
        this.nums[b] = temp;
    }

    private int partition(int left, int right, int pivotIndex) {
        int pivot = this.nums[pivotIndex];
        // 1. move pivot to end
        swap(pivotIndex, right);
        int storeIdex = left;

        // 2. move all smaller elements to the left
        for (int i = left; i < right; i++) {
            if (this.nums[i] < pivot) {
                swap(storeIdex, i);
                storeIdex++;
            }
        }
        // 3. move pivot to its final place
        swap(storeIdex, right);
        return storeIdex;
    }

    private int quickselect(int left, int right, int kSmallest) {
        if (left == right) {
            return this.nums[left];
        }
        Random random = new Random();
        int pivotIndex = left + random.nextInt(right - left);

        pivotIndex = partition(left, right, pivotIndex);
        if (pivotIndex == kSmallest) {
            return this.nums[kSmallest];
        } else if (kSmallest < pivotIndex) {
            return quickselect(left, pivotIndex - 1, kSmallest);
        } else {
            return quickselect(pivotIndex + 1, right, kSmallest);
        }
    }


    /**
     * Runtime: 1 ms, faster than 99.47% of Java online submissions for Kth Largest Element in an Array.
     *
     * Memory Usage: 41.4 MB, less than 5.18% of Java online submissions for Kth Largest Element in an Array.
     *
     * Copy from: https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode/[数组中的第 K 个最大元素 - 数组中的第K个最大元素 - 力扣(LeetCode)]
     */
    public int findKthLargest(int[] nums, int k) {
        this.nums = nums;
        int size = nums.length;
        return quickselect(0, size - 1, size - k);
    }

    /**
     * Runtime: 6 ms, faster than 62.37% of Java online submissions for Kth Largest Element in an Array.
     *
     * Memory Usage: 40.9 MB, less than 5.18% of Java online submissions for Kth Largest Element in an Array.
     */
    public int findKthLargestHeap(int[] nums, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a));
        for (int num : nums) {
            heap.add(num);
            if (heap.size() > k) {
                heap.poll();
            }
        }
        return heap.poll();
    }

    public int findKthLargestSort(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length - k];
    }

    public static void main(String[] args) {
        _0215_KthLargestElementInAnArray solution = new _0215_KthLargestElementInAnArray();
        int[] n1 = {3, 2, 1, 5, 6, 4};
        int r1 = solution.findKthLargest(n1, 2);
        System.out.println((r1 == 5) + " : " + r1);

        int[] n2 = {3, 2, 3, 1, 2, 4, 5, 5, 6};
        int r2 = solution.findKthLargest(n2, 4);
        System.out.println((r2 == 4) + " : " + r2);
    }
}

216. Combination Sum III

Find all possible combinations of *k* numbers that add up to a number *n*, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

  • All numbers will be positive integers.

  • The solution set must not contain duplicate combinations.

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
1
Unresolved directive in 0216-combination-sum-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0216_CombinationSumIII.java[]

217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

Example 3:

Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * = 217. Contains Duplicate
 *
 * https://leetcode.com/problems/contains-duplicate/[Contains Duplicate - LeetCode]
 *
 * Given an array of integers, find if the array contains any duplicates.
 *
 * Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,2,3,1]
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [1,2,3,4]
 * Output: false
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: [1,1,1,3,3,4,3,2,4,2]
 * Output: true
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 20:01
 */
public class _0217_ContainsDuplicate {
    /**
     * Runtime: 9 ms, faster than 58.06% of Java online submissions for Contains Duplicate.
     *
     * Memory Usage: 44.4 MB, less than 57.76% of Java online submissions for Contains Duplicate.
     */
    public boolean containsDuplicate(int[] nums) {
        if (Objects.isNull(nums) || nums.length < 2) {
            return false;
        }
        Set<Integer> numSet = new HashSet<>();
        for (int num : nums) {
            if (numSet.contains(num)) {
                return true;
            } else {
                numSet.add(num);
            }
        }
        return false;
    }

    /**
     * Runtime: 5 ms, faster than 96.50% of Java online submissions for Contains Duplicate.
     *
     * Memory Usage: 42.1 MB, less than 98.28% of Java online submissions for Contains Duplicate.
     */
    public boolean containsDuplicateSort(int[] nums) {
        if (Objects.isNull(nums) || nums.length < 2) {
            return false;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        _0217_ContainsDuplicate solution = new _0217_ContainsDuplicate();
        int[] n1 = {1, 2, 3, 1};
        boolean r1 = solution.containsDuplicate(n1);
        System.out.println(r1);
    }
}

218. The Skyline Problem

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

] </a> <a href="/static/images/problemset/skyline2.jpg" target="_blank"> image::https://assets.leetcode.com/uploads/2018/10/22/skyline2.png[

The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: `[ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] `.

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], …​ ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:`[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ]`.

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].

  • The input list is already sorted in ascending order by the left x position Li.

  • The output list must be sorted by the x position.

  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, […​[2 3], [4 5], [7 5], [11 5], [12 7]…​] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: […​[2 3], [4 5], [12 7], …​]

1
Unresolved directive in 0218-the-skyline-problem.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0218_TheSkylineProblem.java[]

219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false
1
Unresolved directive in 0219-contains-duplicate-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0219_ContainsDuplicateII.java[]

220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
1
Unresolved directive in 0220-contains-duplicate-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0220_ContainsDuplicateIII.java[]

221. Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example:
Input:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

根据左上、左边、上边加自身,确定一个最小正方形;然后再进一步,在小正方形基础上,从四周选择已有正方形中最小,然后扩大,再这个过程中记录下最大的正方形边长,即可得到结果。思路如下图:

0221 1

简化一下,不需要矩阵来存储所有正方形的计算结果,只需要一行来记录上一行计算结果和当前行计算结果即可。

0221 2

参考资料

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example:

Input:

1 0 1 0 0
1 0 <font color="red">1 <font color="red">1 1
1 1 <font color="red">1 <font color="red">1 1
1 0 0 1 0

Output: 4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 221. Maximal Square
 *
 * https://leetcode.com/problems/maximal-square/[Maximal Square - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 12:21
 */
public class _0221_MaximalSquare {

    /**
     * Runtime: 4 ms, faster than 95.17% of Java online submissions for Maximal Square.
     * Memory Usage: 43.3 MB, less than 91.18% of Java online submissions for Maximal Square.
     *
     * Copy from: https://leetcode.com/problems/maximal-square/solution/[Maximal Square solution - LeetCode]
     */
    public int maximalSquare(char[][] matrix) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return 0;
        }
        int yLength = matrix.length;
        int xLength = matrix[0].length;
        int[] dp = new int[xLength + 1];
        int maxSideLength = 0;
        int previous = 0;
        for (int y = 1; y <= yLength; y++) {
            for (int x = 1; x <= xLength; x++) {
                int temp = dp[x];
                if (matrix[y - 1][x - 1] == '1') {
                    dp[x] = Math.min(Math.min(previous, dp[x]), dp[x - 1]) + 1;
                    maxSideLength = Math.max(maxSideLength, dp[x]);
                } else {
                    dp[x] = 0;
                }
                previous = temp;
            }
        }

        return maxSideLength * maxSideLength;
    }

    /**
     * Runtime: 13 ms, faster than 8.65% of Java online submissions for Maximal Square.
     * Memory Usage: 43.9 MB, less than 64.71% of Java online submissions for Maximal Square.
     *
     * Copy from: https://leetcode.com/problems/maximal-square/solution/[Maximal Square solution - LeetCode]
     */
    public int maximalSquareMatrix(char[][] matrix) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return 0;
        }
        int yLength = matrix.length;
        int xLength = matrix[0].length;
        int[][] dp = new int[yLength + 1][xLength + 1];
        int maxSideLength = 0;
        for (int y = 1; y <= yLength; y++) {
            for (int x = 1; x <= xLength; x++) {
                if (matrix[y - 1][x - 1] == '1') {
                    dp[y][x] = Math.min(Math.min(dp[y - 1][x - 1], dp[y - 1][x]), dp[y][x - 1]) + 1;
                    maxSideLength = Math.max(maxSideLength, dp[y][x]);
                }
            }
        }

        return maxSideLength * maxSideLength;
    }

    public static void main(String[] args) {
        _0221_MaximalSquare solution = new _0221_MaximalSquare();
        char[][] m1 = {
                {'1', '0', '1', '0', '0'},
                {'1', '0', '1', '1', '1'},
                {'1', '1', '1', '1', '1'},
                {'1', '0', '0', '1', '0'}
        };
        int r1 = solution.maximalSquare(m1);
        System.out.println((r1 == 4) + " : " + r1);
    }
}

222. Count Complete Tree Nodes

Given a complete binary tree, count the number of nodes.

*Note: *

Definition of a complete binary tree from Wikipedia:

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

Input:
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6
1
Unresolved directive in 0222-count-complete-tree-nodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0222_CountCompleteTreeNodes.java[]

223. Rectangle Area

Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

rectangle area

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

Assume that the total area is never beyond the maximum possible value of int.

1
Unresolved directive in 0223-rectangle-area.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0223_RectangleArea.java[]

224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces ` `.

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23

Note:

  • You may assume that the given expression is always valid.

  • Do not use the eval built-in library function.

1
Unresolved directive in 0224-basic-calculator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0224_BasicCalculator.java[]

225. Implement Stack using Queues

Implement the following operations of a stack using queues.

  • push(x) — Push element x onto stack.

  • pop() — Removes the element on top of the stack.

  • top() — Get the top element.

  • empty() — Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue — which means only push to back, peek/pop from front, size, and is empty operations are valid.

  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.

  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

1
Unresolved directive in 0225-implement-stack-using-queues.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0225_ImplementStackUsingQueues.java[]

226. Invert Binary Tree

Invert a binary tree.

Example:
Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:
     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:

This problem was inspired by this original tweet by Max Howell (@mxcl):

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

D瓜哥也不会做这道题,现在可以说跟大神一个水平了,😆

其实,思路很简单:就是递归地反转每棵树即可。

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:

This problem was inspired by this original tweet by Max Howell:

<blockquote>Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.</blockquote>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 226. Invert Binary Tree
 *
 * https://leetcode.com/problems/invert-binary-tree/[Invert Binary Tree - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 11:33
 */
public class _0226_InvertBinaryTree {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Invert Binary Tree.
     * Memory Usage: 37.1 MB, less than 5.10% of Java online submissions for Invert Binary Tree.
     */
    public TreeNode invertTree(TreeNode root) {
        if (Objects.isNull(root)) {
            return null;
        }
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.right = left;
        root.left = right;
        return root;
    }

    public static void main(String[] args) {
        _0226_InvertBinaryTree solution = new _0226_InvertBinaryTree();
        TreeNode r1 = solution.invertTree(buildTree(Arrays.asList(4, 2, 7, 1, 3, 6, 9)));
        System.out.println(JsonUtils.toJson(r1));
    }
}

227. Basic Calculator II

这里在处理将字符串转成数字时,从左向右按位乘以十再相加的方法,这样就可以只遍历一遍字符串。

另外,这里还有个地方需要注意:在确定当前操作符的情况下,再计算上一次的值。所以,就需要把上一次的值保存下来。

思考题:如果数字是全体整数,又该如何实现?如果再扩容成实数呢?

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces ` `. The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.

  • Do not use the eval built-in library function.

1
Unresolved directive in 0227-basic-calculator-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0227_BasicCalculatorII.java[]

228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.
1
Unresolved directive in 0228-summary-ranges.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0228_SummaryRanges.java[]

229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

*Note: *The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
1
Unresolved directive in 0229-majority-element-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0229_MajorityElementII.java[]

230. Kth Smallest Element in a BST

TODO: 树的非递归遍历还需要多加推敲,加强理解。

0230 1
0230 2
0230 3
0230 4

Given a binary search tree, write a function kthSmallest to find the *k*th smallest element in it.

*Note: *

You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3

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?

1
Unresolved directive in 0230-kth-smallest-element-in-a-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0230_KthSmallestElementInABST.java[]

231. Power of Two

Given an integer, write a function to determine if it is a power of two.

Example 1:

Input: 1
Output: true
Explanation: 2^0^ = 1

Example 2:

Input: 16
Output: true
Explanation: 2^4^ = 16

Example 3:

Input: 218
Output: false
1
Unresolved directive in 0231-power-of-two.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0231_PowerOfTwo.java[]

232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.

  • pop() — Removes the element from in front of queue.

  • peek() — Get the front element.

  • empty() — Return whether the queue is empty.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.

  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

1
Unresolved directive in 0232-implement-queue-using-stacks.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0232_ImplementQueueUsingStacks.java[]

233. Number of Digit One

Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.

Example:

Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
1
Unresolved directive in 0233-number-of-digit-one.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0233_NumberOfDigitOne.java[]

234. Palindrome Linked List

使用快慢指针将链表切成两段,然后对后面的一段进行反转,再逐个比较两个子链。

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Follow up:

Could you do it in O(n) time and O(1) space?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;

/**
 * = 234. Palindrome Linked List
 *
 * Given a singly linked list, determine if it is a palindrome.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 1->2
 * Output: false
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 1->2->2->1
 * Output: true
 * ----
 *
 * *Follow up:*
 *
 * Could you do it in O(n) time and O(1) space?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-13 19:58
 */
public class _0234_PalindromeLinkedList {

    /**
     * Runtime: 1 ms, faster than 99.33% of Java online submissions for Palindrome Linked List.
     *
     * Memory Usage: 41.5 MB, less than 41.46% of Java online submissions for Palindrome Linked List.
     */
    public boolean isPalindrome(ListNode head) {
        if (Objects.isNull(head) || Objects.isNull(head.next)) {
            return true;
        }

        ListNode slow = head;
        ListNode fast = head;
        while (Objects.nonNull(fast) && Objects.nonNull(fast.next)) {
            slow = slow.next;
            fast = fast.next.next;
        }
        slow = reverseList(slow);
        fast = head;
        while (Objects.nonNull(slow)) {
            if (slow.val != fast.val) {
                return false;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }

    private ListNode reverseList(ListNode head) {
        ListNode result = null;
        while (Objects.nonNull(head)) {
            ListNode next = head.next;
            head.next = result;
            result = head;
            head = next;
        }
        return result;
    }

    public static void main(String[] args) {
        _0234_PalindromeLinkedList solution = new _0234_PalindromeLinkedList();
        boolean r1 = solution.isPalindrome(build(Arrays.asList(1, 2, 3, 2, 1)));
        System.out.println(r1);
        boolean r2 = solution.isPalindrome(build(Arrays.asList(1, 2, 3, 3, 2, 1)));
        System.out.println(r2);
        boolean r3 = solution.isPalindrome(build(Arrays.asList(1, 2)));
        System.out.println(r3);
    }
}

235. 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 p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]

binarysearchtree improved

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes' values will be unique.

  • p and q are different and both values will exist in the BST.

1
Unresolved directive in 0235-lowest-common-ancestor-of-a-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0235_LowestCommonAncestorOfABinarySearchTree.java[]

236. Lowest Common Ancestor of a Binary Tree

0236 1

D瓜哥的思路:先找出一条从根节点到某个节点的路径;然后从这条路径上以此去寻找另外一个节点。找到这返回此节点。

思考题:如何按照"路径"的思路实现一遍?

参考资料

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]

binarytree

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes' values will be unique.

  • p and q are different and both values will exist in the binary tree.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 236. Lowest Common Ancestor of a Binary Tree
 *
 * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/[Lowest Common Ancestor of a Binary Tree - LeetCode]
 *
 * Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
 *
 * According to https://en.wikipedia.org/wiki/Lowest_common_ancestor[the definition of LCA on Wikipedia]: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow **a node to be a descendant of itself**).”
 *
 * Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]
 *
 * .Example 1:
 * [source]
 * ----
 * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
 * Output: 3
 * Explanation: The LCA of nodes 5 and 1 is 3.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
 * Output: 5
 * Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
 * ----
 *
 *
 * Note:
 *
 * All of the nodes' values will be unique.
 * p and q are different and both values will exist in the binary tree.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 21:14
 */
public class _0236_LowestCommonAncestorOfABinaryTree {

    private TreeNode result;

    /**
     * Runtime: 9 ms, faster than 23.17% of Java online submissions for Lowest Common Ancestor of a Binary Tree.
     *
     * Memory Usage: 45.5 MB, less than 5.55% of Java online submissions for Lowest Common Ancestor of a Binary Tree.
     *
     * Copy from: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/[Lowest Common Ancestor of a Binary Tree solution - LeetCode]
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        recurseTree(root, p, q);
        return this.result;
    }

    private boolean recurseTree(TreeNode currentNode, TreeNode p, TreeNode q) {
        if (Objects.isNull(currentNode)) {
            return false;
        }

        int left = recurseTree(currentNode.left, p, q) ? 1 : 0;

        int right = recurseTree(currentNode.right, p, q) ? 1 : 0;

        int mid = (currentNode.equals(p) || currentNode.equals(q)) ? 1 : 0;

        if (left + mid + right >= 2) {
            this.result = currentNode;
        }
        return (left + mid + right) > 0;
    }

    public static void main(String[] args) {
        _0236_LowestCommonAncestorOfABinaryTree solution = new _0236_LowestCommonAncestorOfABinaryTree();
        TreeNode r1 = solution.lowestCommonAncestor(buildTree(Arrays.asList(3, 5, 1, 6, 2, 0, 8, null, null, 7, 4)), new TreeNode(5), new TreeNode(1));
        System.out.println((r1.val == 3) + " : " + r1);

        TreeNode r2 = solution.lowestCommonAncestor(buildTree(Arrays.asList(3, 5, 1, 6, 2, 0, 8, null, null, 7, 4)), new TreeNode(5), new TreeNode(4));
        System.out.println((r2.val == 3) + " : " + r2);
    }
}

237. Delete Node in a Linked List

这个题其实很简单!把节点的值覆盖当前节点的值即可。

没想到打脸如此之快!还有更简单的办法,两行代码搞定:①把下一个节点的值拷贝到当前节点;②把当前节点的下一节点指向下下一个节点即可。

0237 0
0237 1
0237 2

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list — head = [4,5,1,9], which looks like following:

237 example

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.

  • All of the nodes' values will be unique.

  • The given node will not be the tail and it will always be a valid node of the linked list.

  • Do not return anything from your function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 237. 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.
 *
 * Given linked list -- head = [4,5,1,9], which looks like following:
 *
 * .Example 2:
 * [source]
 * ----
 * Input: head = [4,5,1,9], node = 5
 * Output: [4,1,9]
 * Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input: head = [4,5,1,9], node = 1
 * Output: [4,5,9]
 * Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
 * ----
 *
 * *Note:*
 *
 * * The linked list will have at least two elements.
 * * All of the nodes' values will be unique.
 * * The given node will not be the tail and it will always be a valid node of the linked list.
 * * Do not return anything from your function.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-13 20:28
 */
public class _0237_DeleteNodeInALinkedList {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Delete Node in a Linked List.
     *
     * Memory Usage: 36.2 MB, less than 100.00% of Java online submissions for Delete Node in a Linked List.
     *
     * Copy from: https://leetcode.com/problems/delete-node-in-a-linked-list/solution/[Delete Node in a Linked List solution - LeetCode]
     */
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Delete Node in a Linked List.
     *
     * Memory Usage: 36.5 MB, less than 100.00% of Java online submissions for Delete Node in a Linked List.
     */
    public void deleteNodeCopyList(ListNode node) {
        ListNode current = node;
        while (Objects.nonNull(current) && Objects.nonNull(current.next)) {
            ListNode next = current.next;
            current.val = next.val;
            if (Objects.nonNull(next.next)) {
                current = next;
            } else {
                current.next = null;
            }
        }
    }

    public static void main(String[] args) {
        _0237_DeleteNodeInALinkedList solution = new _0237_DeleteNodeInALinkedList();
        ListNode l1 = build(Arrays.asList(1, 2, 3));
        solution.deleteNode(l1);
        printListNode(l1);
    }
}

238. Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: *Please solve it *without division and in O(n).

Follow up:

Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 238. Product of Array Except Self
 *
 * https://leetcode.com/problems/product-of-array-except-self/[Product of Array Except Self - LeetCode]
 *
 * Given an array `nums` of `n` integers where `n > 1`,  return an array `output` such that `output[i]` is equal to the product of all the elements of `nums` except `nums[i]`.
 *
 * .Example:
 * [source]
 * ----
 * Input:  [1,2,3,4]
 * Output: [24,12,8,6]
 * ----
 *
 * *Note:* Please solve it *without division* and in O(n).
 *
 * *Follow up:*
 *
 * Could you solve it with constant space complexity? (The output array *does not* count as extra space for the purpose of space complexity analysis.)
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 20:15
 */
public class _0238_ProductOfArrayExceptSelf {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Product of Array Except Self.
     *
     * Memory Usage: 42.8 MB, less than 48.03% of Java online submissions for Product of Array Except Self.
     */
    public int[] productExceptSelf(int[] nums) {
        int[] result = new int[nums.length];
        result[0] = 1;
        for (int i = 1; i < nums.length; i++) {
            result[i] = nums[i - 1] * result[i - 1];
        }
        int temp = 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            result[i] *= temp;
            temp *= nums[i];
        }
        return result;
    }

    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Product of Array Except Self.
     *
     * Memory Usage: 42.8 MB, less than 48.03% of Java online submissions for Product of Array Except Self.
     */
    public int[] productExceptSelfDivision(int[] nums) {
        int product = 1;
        int zero = nums.length;
        for (int num : nums) {
            if (num == 0) {
                zero++;
                continue;
            }
            product *= num;
        }

        int[] result = new int[nums.length];
        if (zero >= nums.length + 2) {
            return result;
        }
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (num == 0) {
                result[i] = product;
            } else {
                if (zero == nums.length + 1) {
                    result[i] = 0;
                } else {
                    result[i] = product / num;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0238_ProductOfArrayExceptSelf solution = new _0238_ProductOfArrayExceptSelf();
        int[] a1 = {1, 2, 3, 4};
        int[] r1 = solution.productExceptSelf(a1);
        int[] sr1 = {24, 12, 8, 6};
        System.out.println(Arrays.equals(r1, sr1) + " : " + Arrays.toString(r1));

        int[] a2 = {0, 0};
        int[] r2 = solution.productExceptSelf(a2);
        int[] sr2 = {0, 0};
        System.out.println(Arrays.equals(r2, sr2) + " : " + Arrays.toString(r2));
    }
}

239. Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Note:

You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:

Could you solve it in linear time?

解题分析

0239 1
0239 2
0239 3
0239 4
0239 5

思考题

思考一下动态规划解法的正确性!

参考资料

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

*Note: *

You may assume k is always valid, 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:

Could you solve it in linear time?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * = 239. Sliding Window Maximum
 *
 * https://leetcode.com/problems/sliding-window-maximum/[Sliding Window Maximum - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 17:00
 */
public class _0239_SlidingWindowMaximum {
    /**
     * Runtime: 9 ms, faster than 85.37% of Java online submissions for Sliding Window Maximum.
     * Memory Usage: 56.6 MB, less than 6.25% of Java online submissions for Sliding Window Maximum.
     *
     * Copy from: https://leetcode-cn.com/problems/sliding-window-maximum/solution/hua-dong-chuang-kou-zui-da-zhi-by-leetcode-3/[滑动窗口最大值 - 滑动窗口最大值 - 力扣(LeetCode)]
     */
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (Objects.isNull(nums) || nums.length == 0 || k == 0) {
            return new int[0];
        }
        if (k == 1) {
            return nums;
        }
        int n = nums.length;
        int[] left = new int[n];
        left[0] = nums[0];
        int[] right = new int[n];
        right[n - 1] = nums[n - 1];
        for (int i = 1; i < n; i++) {
            if (i % k == 0) {
                left[i] = nums[i];
            } else {
                left[i] = Math.max(left[i - 1], nums[i]);
            }

            int j = n - i - 1;
            if ((j + 1) % k == 0) {
                right[j] = nums[j];
            } else {
                right[j] = Math.max(nums[j], right[j + 1]);
            }
        }

        int[] result = new int[n - k + 1];
        for (int i = 0; i < n - k + 1; i++) {
            result[i] = Math.max(left[i + k - 1], right[i]);
        }

        return result;
    }

    /**
     * Runtime: 25 ms, faster than 30.23% of Java online submissions for Sliding Window Maximum.
     * Memory Usage: 48.5 MB, less than 6.25% of Java online submissions for Sliding Window Maximum.
     */
    public int[] maxSlidingWindowMax(int[] nums, int k) {
        if (Objects.isNull(nums) || nums.length == 0 || k == 0) {
            return new int[0];
        }
        List<Integer> integers = new ArrayList<>();
        for (int i = 0; i < nums.length - k + 1; i++) {
            int max = Integer.MIN_VALUE;
            for (int j = i; j < i + k; j++) {
                max = Math.max(max, nums[j]);
            }
            integers.add(max);
        }
        int[] result = new int[integers.size()];
        for (int i = 0; i < integers.size(); i++) {
            result[i] = integers.get(i);
        }
        return result;
    }

    public static void main(String[] args) {
        _0239_SlidingWindowMaximum solution = new _0239_SlidingWindowMaximum();
        int[] n1 = {1, 3, -1, -3, 5, 3, 6, 7};
        int[] r1 = solution.maxSlidingWindow(n1, 5);
        System.out.println(Arrays.toString(r1));
    }
}

240. Search a 2D Matrix II

从右上角开始搜索,小则下移,大则左移,这个方案真是精妙!

0240 1

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.

  • Integers in each column are sorted in ascending from top to bottom.

Example:

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 240. Search a 2D Matrix II
 *
 * https://leetcode.com/problems/search-a-2d-matrix-ii/[(1) Search a 2D Matrix II - LeetCode]
 *
 * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
 *
 * * Integers in each row are sorted in ascending from left to right.
 * * Integers in each column are sorted in ascending from top to bottom.
 *
 * *Example:*
 *
 * Consider the following matrix:
 *
 * ----
 * [
 *   [1,   4,  7, 11, 15],
 *   [2,   5,  8, 12, 19],
 *   [3,   6,  9, 16, 22],
 *   [10, 13, 14, 17, 24],
 *   [18, 21, 23, 26, 30]
 * ]
 * ----
 *
 * Given target = `5`, return `true`.
 *
 * Given target = `20`, return `false`.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-23 10:04
 */
public class _0240_SearchA2DMatrixII {
    /**
     * Runtime: 5 ms, faster than 99.96% of Java online submissions for Search a 2D Matrix II.
     *
     * Memory Usage: 50.3 MB, less than 5.66% of Java online submissions for Search a 2D Matrix II.
     *
     * Copy from: https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/66140/My-concise-O(m%2Bn)-Java-solution[(1) My concise O(m+n) Java solution - LeetCode Discuss]
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        if (Objects.isNull(matrix) || matrix.length == 0) {
            return false;
        }
        int column = 0;
        int row = matrix[0].length - 1;
        while (column < matrix.length && 0 <= row) {
            int value = matrix[column][row];
            if (value == target) {
                return true;
            } else if (value < target) {
                column++;
            } else if (value > target) {
                row--;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        _0240_SearchA2DMatrixII solution = new _0240_SearchA2DMatrixII();
        int[][] m1 = {
                {1, 4, 7, 11, 15},
                {2, 5, 8, 12, 19},
                {3, 6, 9, 16, 22},
                {10, 13, 14, 17, 24},
                {18, 21, 23, 26, 30}
        };
        boolean r1 = solution.searchMatrix(m1, 5);
        System.out.println(r1);

        boolean r2 = solution.searchMatrix(m1, 20);
        System.out.println(!r2);
    }
}

241. Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1:

Input: "2-1-1"
Output: [0, 2]
Explanation:
2-1)-1) = 0 (2-(1-1 = 2

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(2(3-(45))) = -34
23)-(45 = -14
2(3-45) = -10
(23-4)5 = -10
(((23)-4)5) = 10
1
Unresolved directive in 0241-different-ways-to-add-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0241_DifferentWaysToAddParentheses.java[]

242. Valid Anagram

两种解法都可以,还是要多做题啊!

Given two strings s and t _, write a function to determine if _t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:

You may assume the string contains only lowercase alphabets.

Follow up:

What if the inputs contain unicode characters? How would you adapt your solution to such case?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 242. Valid Anagram
 *
 * Given two strings `s` and `t` , write a function to determine if `t` is an anagram of `s`.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: s = "anagram", t = "nagaram"
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: s = "rat", t = "car"
 * Output: false
 * ----
 *
 * *Note:*
 * You may assume the string contains only lowercase alphabets.
 *
 * *Follow up:*
 *
 * What if the inputs contain unicode characters? How would you adapt your solution to such case?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-10 23:48
 */
public class _0242_ValidAnagram {
    /**
     * Runtime: 3 ms, faster than 93.97% of Java online submissions for Valid Anagram.
     *
     * Memory Usage: 36.2 MB, less than 98.06% of Java online submissions for Valid Anagram.
     */
    public boolean isAnagram(String s, String t) {
        if (Objects.isNull(s) && Objects.isNull(t)) {
            return true;
        }
        if (Objects.isNull(s) || Objects.isNull(t)) {
            return false;
        }
        int[] sChartCount = new int[26];
        for (char c : s.toCharArray()) {
            sChartCount[c - 'a']++;
        }
        int[] tChartCount = new int[26];
        for (char c : t.toCharArray()) {
            tChartCount[c - 'a']++;
        }
        return Arrays.equals(sChartCount, tChartCount);
    }

    /**
     * Runtime: 3 ms, faster than 93.97% of Java online submissions for Valid Anagram.
     *
     * Memory Usage: 37.9 MB, less than 64.51% of Java online submissions for Valid Anagram.
     */
    public boolean isAnagramSort(String s, String t) {
        char[] sChars = s.toCharArray();
        Arrays.sort(sChars);
        char[] tChars = t.toCharArray();
        Arrays.sort(tChars);
        return Arrays.equals(sChars, tChars);
    }

    public static void main(String[] args) {
        _0242_ValidAnagram solution = new _0242_ValidAnagram();
        boolean r1 = solution.isAnagram("anagram", "nagaram");
        System.out.println(r1);

        boolean r2 = solution.isAnagram("rat", "car");
        System.out.println(r2);
    }
}

243. Shortest Word Distance

1
Unresolved directive in 0243-shortest-word-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0243_ShortestWordDistance.java[]

244. Shortest Word Distance II

1
Unresolved directive in 0244-shortest-word-distance-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0244_ShortestWordDistanceII.java[]

245. Shortest Word Distance III

1
Unresolved directive in 0245-shortest-word-distance-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0245_ShortestWordDistanceIII.java[]

246. Strobogrammatic Number

1
Unresolved directive in 0246-strobogrammatic-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0246_StrobogrammaticNumber.java[]

247. Strobogrammatic Number II

1
Unresolved directive in 0247-strobogrammatic-number-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0247_StrobogrammaticNumberII.java[]

248. Strobogrammatic Number III

1
Unresolved directive in 0248-strobogrammatic-number-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0248_StrobogrammaticNumberIII.java[]

249. Group Shifted Strings

1
Unresolved directive in 0249-group-shifted-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0249_GroupShiftedStrings.java[]

250. Count Univalue Subtrees

1
Unresolved directive in 0250-count-univalue-subtrees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0250_CountUnivalueSubtrees.java[]

251. Flatten 2D Vector

1
Unresolved directive in 0251-flatten-2d-vector.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0251_Flatten2DVector.java[]

252. Meeting Rooms

1
Unresolved directive in 0252-meeting-rooms.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0252_MeetingRooms.java[]

253. Meeting Rooms II

1
Unresolved directive in 0253-meeting-rooms-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0253_MeetingRoomsII.java[]

254. Factor Combinations

1
Unresolved directive in 0254-factor-combinations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0254_FactorCombinations.java[]

255. Verify Preorder Sequence in Binary Search Tree

1
Unresolved directive in 0255-verify-preorder-sequence-in-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0255_VerifyPreorderSequenceInBinarySearchTree.java[]

256. Paint House

1
Unresolved directive in 0256-paint-house.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0256_PaintHouse.java[]

257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3
1
Unresolved directive in 0257-binary-tree-paths.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0257_BinaryTreePaths.java[]

258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2
Explanation: 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?

1
Unresolved directive in 0258-add-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0258_AddDigits.java[]

259. 3Sum Smaller

1
Unresolved directive in 0259-3sum-smaller.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0259_3SumSmaller.java[]

260. Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Example:

Input:  [1,2,1,3,2,5]
Output: [3,5]

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.

  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

1
Unresolved directive in 0260-single-number-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0260_SingleNumberIII.java[]

261. Graph Valid Tree

1
Unresolved directive in 0261-graph-valid-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0261_GraphValidTree.java[]

262. Trips and Users

The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’).

-----------------------------------------------------------------+
| Id | Client_Id | Driver_Id | City_Id |        Status      |Request_at|
-----------------------------------------------------------------+
| 1  |     1     |    10     |    1    |     completed      |2013-10-01|
| 2  |     2     |    11     |    1    | cancelled_by_driver|2013-10-01|
| 3  |     3     |    12     |    6    |     completed      |2013-10-01|
| 4  |     4     |    13     |    6    | cancelled_by_client|2013-10-01|
| 5  |     1     |    10     |    1    |     completed      |2013-10-02|
| 6  |     2     |    11     |    6    |     completed      |2013-10-02|
| 7  |     3     |    12     |    6    |     completed      |2013-10-02|
| 8  |     2     |    12     |    12   |     completed      |2013-10-03|
| 9  |     3     |    10     |    12   |     completed      |2013-10-03|
| 10 |     4     |    13     |    12   | cancelled_by_driver|2013-10-03|
-----------------------------------------------------------------+

The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘client’, ‘driver’, ‘partner’).

--------------------------
| Users_Id | Banned |  Role  |
--------------------------
|    1     |   No   | client |
|    2     |   Yes  | client |
|    3     |   No   | client |
|    4     |   No   | client |
|    10    |   No   | driver |
|    11    |   No   | driver |
|    12    |   No   | driver |
|    13    |   No   | driver |
--------------------------

Write a SQL query to find the cancellation rate of requests made by unbanned users (both client and driver must be unbanned) between Oct 1, 2013 and Oct 3, 2013. The cancellation rate is computed by dividing the number of canceled (by client or driver) requests made by unbanned users by the total number of requests made by unbanned users.

For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places.

-------------------------------+
|     Day    | Cancellation Rate |
-------------------------------+
| 2013-10-01 |       0.33        |
| 2013-10-02 |       0.00        |
| 2013-10-03 |       0.50        |
-------------------------------+

Credits:

Special thanks to <a href="https://leetcode.com/discuss/user/cak1erlizhou">@cak1erlizhou</a> for contributing this question, writing the problem description and adding part of the test cases.

1
Unresolved directive in 0262-trips-and-users.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0262_TripsAndUsers.java[]

263. Ugly Number

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Example 1:

Input: 6
Output: true
Explanation: 6 = 2 &times; 3

Example 2:

Input: 8
Output: true
Explanation: 8 = 2 &times; 2 &times; 2

Example 3:

Input: 14
Output: false
Explanation: 14 is not ugly since it includes another prime factor 7.

Note:

  1. 1 is typically treated as an ugly number.

  2. Input is within the 32-bit signed integer range: [-231, 2^31 ^- 1].

1
Unresolved directive in 0263-ugly-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0263_UglyNumber.java[]

264. Ugly Number II

Write a program to find the n-th ugly number.

Ugly numbers are* positive numbers* whose prime factors only include 2, 3, 5.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

*Note: *

  1. 1 is typically treated as an ugly number.

  2. n does not exceed 1690.

1
Unresolved directive in 0264-ugly-number-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0264_UglyNumberII.java[]

265. Paint House II

1
Unresolved directive in 0265-paint-house-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0265_PaintHouseII.java[]

266. Palindrome Permutation

1
Unresolved directive in 0266-palindrome-permutation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0266_PalindromePermutation.java[]

267. Palindrome Permutation II

1
Unresolved directive in 0267-palindrome-permutation-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0267_PalindromePermutationII.java[]

268. Missing Number

这道题跟 41. First Missing Positive 很像!

Given an array containing n distinct numbers taken from 0, 1, 2, …​, n, find the one that is missing from the array.

Example 1:

Input: [3,0,1]
Output: 2

Example 2:

Input: [9,6,4,2,3,5,7,0,1]
Output: 8

Note:

Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 268. Missing Number
 *
 * https://leetcode.com/problems/missing-number/[Missing Number - LeetCode]
 *
 * Given an array containing n distinct numbers taken from `0, 1, 2, ..., n`, find the one that is missing from the array.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [3,0,1]
 * Output: 2
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [9,6,4,2,3,5,7,0,1]
 * Output: 8
 * ----
 *
 * *Note:*
 *
 * Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 21:30
 */
public class _0268_MissingNumber {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Missing Number.
     *
     * Memory Usage: 38.9 MB, less than 100.00% of Java online submissions for Missing Number.
     *
     * Copy from: https://leetcode.com/problems/missing-number/solution/[Missing Number solution - LeetCode]
     */
    public int missingNumber(int[] nums) {
        int actualSum = 0;
        for (int num : nums) {
            actualSum += num;
        }
        int expectSum = nums.length * (nums.length + 1) / 2;
        return expectSum - actualSum;
    }

    /**
     * Runtime: 7 ms, faster than 24.02% of Java online submissions for Missing Number.
     *
     * Memory Usage: 39.8 MB, less than 100.00% of Java online submissions for Missing Number.
     */
    public int missingNumberSort(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i) {
                return i;
            }
        }
        if (nums[nums.length - 1] == nums.length - 1) {
            return nums.length;
        }
        return -1;
    }

    public static void main(String[] args) {
        _0268_MissingNumber solution = new _0268_MissingNumber();
        int[] a1 = {3, 0, 1};
        int r1 = solution.missingNumber(a1);
        System.out.println((r1 == 2) + " : " + r1);

        int[] a2 = {9, 6, 4, 2, 3, 5, 7, 0, 1};
        int r2 = solution.missingNumber(a2);
        System.out.println((r2 == 8) + " : " + r2);
    }
}

269. Alien Dictionary

1
Unresolved directive in 0269-alien-dictionary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0269_AlienDictionary.java[]

270. Closest Binary Search Tree Value

1
Unresolved directive in 0270-closest-binary-search-tree-value.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0270_ClosestBinarySearchTreeValue.java[]

271. Encode and Decode Strings

1
Unresolved directive in 0271-encode-and-decode-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0271_EncodeAndDecodeStrings.java[]

272. Closest Binary Search Tree Value II

1
Unresolved directive in 0272-closest-binary-search-tree-value-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0272_ClosestBinarySearchTreeValueII.java[]

273. Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.

Example 1:

Input: 123
Output: "One Hundred Twenty Three"

Example 2:

Input: 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

Example 4:

Input: 1234567891
Output: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
1
Unresolved directive in 0273-integer-to-english-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0273_IntegerToEnglishWords.java[]

274. H-Index

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:

Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had
             received 3, 0, 6, 1, 5 citations respectively.
             Since the researcher has 3 papers with at least 3 citations each and the remaining
             two with no more than 3 citations each, her h-index is 3.

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

1
Unresolved directive in 0274-h-index.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0274_HIndex.java[]

275. H-Index II

Given an array of citations *sorted in ascending order *(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:

Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
             received 0, 1, 3, 5, 6 citations respectively.
             Since the researcher has 3 papers with at least 3 citations each and the remaining
             two with no more than 3 citations each, her h-index is 3.

Note:

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

Follow up:

  • This is a follow up problem to <a href="/problems/h-index/description/">H-Index</a>, where citations is now guaranteed to be sorted in ascending order.

  • Could you solve it in logarithmic time complexity?

1
Unresolved directive in 0275-h-index-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0275_HIndexII.java[]

276. Paint Fence

1
Unresolved directive in 0276-paint-fence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0276_PaintFence.java[]

277. Find the Celebrity

1
Unresolved directive in 0277-find-the-celebrity.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0277_FindTheCelebrity.java[]

278. First Bad Version

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …​, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 
1
Unresolved directive in 0278-first-bad-version.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0278_FirstBadVersion.java[]

279. Perfect Squares

当前节点最小的值为当前值减去一个平方对应数字的值再加一,再众多选项中的最小值。

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …​) which sum to n.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.diguage.algorithm.leetcode;

/**
 * = 279. Perfect Squares
 *
 * https://leetcode.com/problems/perfect-squares/[Perfect Squares - LeetCode]
 *
 * Given a positive integer n, find the least number of perfect square numbers (for example, `1`, `4`, `9`, `16`, `...`) which sum to n.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: n = 12
 * Output: 3
 * Explanation: 12 = 4 + 4 + 4.
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: n = 13
 * Output: 2
 * Explanation: 13 = 4 + 9.
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-24 11:34
 */
public class _0279_PerfectSquares {
    /**
     * Runtime: 45 ms, faster than 31.57% of Java online submissions for Perfect Squares.
     *
     * Memory Usage: 41.2 MB, less than 13.89% of Java online submissions for Perfect Squares.
     *
     * Copy from:
     */
    public int numSquares(int n) {
        if (n <= 0) {
            return 0;
        }
        int[] dp = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            dp[i] = i; // 最坏的情况就是每次+1,也就是分解为 i 个 1*1
            for (int j = 1; i - j * j >= 0; j++) {
                dp[i] = Math.min(dp[i], dp[i - j * j] + 1);
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        _0279_PerfectSquares solution = new _0279_PerfectSquares();
        int r1 = solution.numSquares(12);
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.numSquares(13);
        System.out.println((r2 == 2) + " : " + r2);
    }
}

280. Wiggle Sort

1
Unresolved directive in 0280-wiggle-sort.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0280_WiggleSort.java[]

281. Zigzag Iterator

1
Unresolved directive in 0281-zigzag-iterator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0281_ZigzagIterator.java[]

282. Expression Add Operators

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.

Example 1:

Input: num = "123", target = 6
Output: ["1+2+3", "1*2*3"]

Example 2:

Input: num = "232", target = 8
Output: ["2*3+2", "2+3*2"]

Example 3:

Input: num = "105", target = 5
Output: ["1*0+5","10-5"]

Example 4:

Input: num = "00", target = 0
Output: ["0+0", "0-0", "0*0"]

Example 5:

Input: num = "3456237490", target = 9191
Output: []
1
Unresolved directive in 0282-expression-add-operators.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0282_ExpressionAddOperators.java[]

283. Move Zeroes

每次答案都比我写的简洁!

Given an array nums, write a function to move all `0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.

  2. Minimize the total number of operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 283. Move Zeroes
 *
 * https://leetcode.com/problems/move-zeroes/[Move Zeroes - LeetCode]
 *
 * Given an array `nums`, write a function to move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.
 *
 * .Example:
 * [source]
 * ----
 * Input: [0,1,0,3,12]
 * Output: [1,3,12,0,0]
 * ----
 *
 * *Note:*
 *
 * . You must do this *in-place* without making a copy of the array.
 * . Minimize the total number of operations.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 22:26
 */
public class _0283_MoveZeroes {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Move Zeroes.
     *
     * Memory Usage: 38 MB, less than 93.01% of Java online submissions for Move Zeroes.
     */
    public void moveZeroes(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                count++;
                continue;
            }
            nums[i - count] = nums[i];
        }
        for (int i = nums.length - count; i < nums.length; i++) {
            nums[i] = 0;
        }
    }

    public static void main(String[] args) {
        _0283_MoveZeroes solution = new _0283_MoveZeroes();
        int[] a1 = {0, 1, 0, 3, 12};
        solution.moveZeroes(a1);
        int[] r1 = {1, 3, 12, 0, 0};
        System.out.println(Arrays.equals(a1, r1) + " : " + Arrays.toString(a1));
    }
}

284. Peeking Iterator

Given an Iterator class interface with methods: next() and hasNext(), design and implement a PeekingIterator that support the peek() operation — it essentially peek() at the element that will be returned by the next call to next().

Example:

Assume that the iterator is initialized to the beginning of the list: [1,2,3].

Call next() gets you 1, the first element in the list.
Now you call peek() and it returns 2, the next element. Calling next() after that still return 2.
You call next() the final time and it returns 3, the last element.
Calling hasNext() after that should return false.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

1
Unresolved directive in 0284-peeking-iterator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0284_PeekingIterator.java[]

285. Inorder Successor in BST

1
Unresolved directive in 0285-inorder-successor-in-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0285_InorderSuccessorInBST.java[]

286. Walls and Gates

1
Unresolved directive in 0286-walls-and-gates.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0286_WallsAndGates.java[]

287. Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 1:
Input: [3,1,3,4,2]
Output: 3

Note:

  • You must not modify the array (assume the array is read only).

  • You must use only constant, \(O\left(1\right)\) extra space.

  • Your runtime complexity should be less than \(O\left(n^{2}\right)\).

  • There is only one duplicate number in the array, but it could be repeated more than once.

可以使用 142. Linked List Cycle II 中的 Floyd’s Tortoise and Hare (Cycle Detection) 算法来解决。

参考资料

  1. Find the Duplicate Number solution - LeetCode 中 Approach #3 Floyd’s Tortoise and Hare (Cycle Detection) [Accepted] 的好精巧!类似于在链表中发现环。还需要再仔细思考一下这个问题!

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

Input: [1,3,4,2,2]
Output: 2

Example 2:

Input: [3,1,3,4,2]
Output: 3

Note:

  1. You must not modify the array (assume the array is read only).

  2. You must use only constant, O(1) extra space.

  3. Your runtime complexity should be less than O(n2).

  4. There is only one duplicate number in the array, but it could be repeated more than once.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.diguage.algorithm.leetcode;

/**
 * = 287. Find the Duplicate Number
 *
 * https://leetcode.com/problems/find-the-duplicate-number/[Find the Duplicate Number - LeetCode]
 *
 * Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,3,4,2,2]
 * Output: 2
 * ----
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [3,1,3,4,2]
 * Output: 3
 * ----
 *
 * *Note:*
 *
 * . You *must not* modify the array (assume the array is read only).
 * . You must use only constant, O(1) extra space.
 * . Your runtime complexity should be less than O(n^2^).
 * . There is only one duplicate number in the array, but it could be repeated more than once.
 *
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 22:52
 */
public class _0287_FindTheDuplicateNumber {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Find the Duplicate Number.
     * Memory Usage: 42.8 MB, less than 5.09% of Java online submissions for Find the Duplicate Number.
     *
     * Copy from: https://leetcode.com/problems/find-the-duplicate-number/solution/[Find the Duplicate Number - LeetCode]
     */
    public int findDuplicate(int[] nums) {
        int tortoise = nums[0];
        int hare = nums[0];
        do {
            tortoise = nums[tortoise];
            hare = nums[nums[hare]];
        } while (tortoise != hare);

        int pointer1 = nums[0];
        int pointer2 = hare;

        while (pointer1 != pointer2) {
            pointer1 = nums[pointer1];
            pointer2 = nums[pointer2];
        }
        return pointer1;
    }

    /**
     * Runtime: 95 ms, faster than 5.83% of Java online submissions for Find the Duplicate Number.
     *
     * Memory Usage: 37.8 MB, less than 37.29% of Java online submissions for Find the Duplicate Number.
     */
    public int findDuplicateBruteForce(int[] nums) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    return nums[i];
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        _0287_FindTheDuplicateNumber solution = new _0287_FindTheDuplicateNumber();
        int[] a1 = {1, 3, 4, 2, 2};
        int r1 = solution.findDuplicate(a1);
        System.out.println((r1 == 2) + " : " + r1);

        int[] a2 = {3, 1, 3, 4, 2};
        int r2 = solution.findDuplicate(a2);
        System.out.println((r2 == 3) + " : " + r2);
    }
}

288. Unique Word Abbreviation

1
Unresolved directive in 0288-unique-word-abbreviation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0288_UniqueWordAbbreviation.java[]

289. Game of Life

According to the Wikipedia’s article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.

  2. Any live cell with two or three live neighbors lives on to the next generation.

  3. Any live cell with more than three live neighbors dies, as if by over-population..

  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input:
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]

Output:
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.

  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package com.diguage.algorithm.leetcode;

import java.util.Objects;

import static com.diguage.algorithm.util.PrintUtils.printMatrix;

/**
 * = 289. Game of Life
 *
 * https://leetcode.com/problems/game-of-life/[Game of Life - LeetCode]
 *
 * According to the https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life[Wikipedia's article]:
 * "The **Game of Life**, also known simply as *Life*, is a cellular automaton devised by the
 * British mathematician John Horton Conway in 1970."
 *
 * Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each
 * cell interacts with its https://en.wikipedia.org/wiki/Moore_neighborhood[eight neighbors]
 * (horizontal, vertical, diagonal) using the following four rules (taken from the above
 * Wikipedia article):
 *
 * . Any live cell with fewer than two live neighbors dies, as if caused by under-population.
 * . Any live cell with two or three live neighbors lives on to the next generation.
 * . Any live cell with more than three live neighbors dies, as if by over-population..
 * . Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
 *
 * Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.
 *
 * .Example:
 * [source]
 * ----
 * Input:
 * [
 *   [0,1,0],
 *   [0,0,1],
 *   [1,1,1],
 *   [0,0,0]
 * ]
 * Output:
 * [
 *   [0,0,0],
 *   [1,0,1],
 *   [0,1,1],
 *   [0,1,0]
 * ]
 * ----
 *
 * *Follow up:*
 *
 * . Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
 * . In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2019-10-29 00:01
 */
public class _0289_GameOfLife {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Game of Life.
     *
     * Memory Usage: 35.1 MB, less than 100.00% of Java online submissions for Game of Life.
     */
    public void gameOfLife(int[][] board) {
        if (Objects.isNull(board) || board.length == 0 || board[0].length == 0) {
            return;
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                board[i][j] = countOfLive(board, i, j);
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                int value = 0;
                if (isLive(board, i, j)) {
                    value = 1;
                }
                board[i][j] = value;
            }
        }
    }

    private boolean isLive(int[][] matrix, int i, int j) {
        int value = matrix[i][j];
        if (value == 12 || value == 13 || value == -3) {
            return true;
        } else {
            return false;
        }
    }

    private int countOfLive(int[][] matrix, int i, int j) {
        int count = 0;
        int value = matrix[i][j];
        int iLength = matrix.length;
        int jLength = matrix[0].length;


        if (i - 1 >= 0) {
            if (j - 1 >= 0) {
                count += matrix[i - 1][j - 1] > 0 ? 1 : 0;
            }

            count += matrix[i - 1][j] > 0 ? 1 : 0;

            if (j + 1 < jLength) {
                count += matrix[i - 1][j + 1] > 0 ? 1 : 0;
            }
        }

        if (j - 1 >= 0) {
            count += matrix[i][j - 1] > 0 ? 1 : 0;
        }
        if (j + 1 < jLength) {
            count += matrix[i][j + 1] > 0 ? 1 : 0;
        }

        if (i + 1 < iLength) {
            if (j - 1 >= 0) {
                count += matrix[i + 1][j - 1] > 0 ? 1 : 0;
            }

            count += matrix[i + 1][j] > 0 ? 1 : 0;

            if (j + 1 < jLength) {
                count += matrix[i + 1][j + 1] > 0 ? 1 : 0;
            }
        }

        if (value > 0) {
            return count + 10;
        } else {
            return -count;
        }
    }

    public static void main(String[] args) {
        _0289_GameOfLife solution = new _0289_GameOfLife();
        int[][] matrix = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
        printMatrix(matrix);
        solution.gameOfLife(matrix);
        printMatrix(matrix);
    }
}

290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:

You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.

1
Unresolved directive in 0290-word-pattern.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0290_WordPattern.java[]

291. Word Pattern II

1
Unresolved directive in 0291-word-pattern-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0291_WordPatternII.java[]

292. Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

Example:

Input: 4
Output: false
Explanation: If there are 4 stones in the heap, then you will never win the game;
             No matter 1, 2, or 3 stones you remove, the last stone will always be
             removed by your friend.
1
Unresolved directive in 0292-nim-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0292_NimGame.java[]

293. Flip Game

1
Unresolved directive in 0293-flip-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0293_FlipGame.java[]

294. Flip Game II

1
Unresolved directive in 0294-flip-game-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0294_FlipGameII.java[]

295. Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.

  • double findMedian() - Return the median of all elements so far.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

Follow up:

  • If all integer numbers from the stream are between 0 and 100, how would you optimize it?

  • If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

1
Unresolved directive in 0295-find-median-from-data-stream.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0295_FindMedianFromDataStream.java[]

296. Best Meeting Point

1
Unresolved directive in 0296-best-meeting-point.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0296_BestMeetingPoint.java[]

297. Serialize and Deserialize Binary Tree

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

*Example: *

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]"

Clarification: The above format is the same as <a href="/faq/#binary-tree">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

*Note: *Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

解题分析

一个比较简单的思路是分层进行序列化。这里一个误区就是把二叉树按照满二叉树转化成一个数组形式。

一个解决办法就是:在序列化的时候,先出力父节点,然后循环调用处理子节点,这样的话,就会把父子节点的关联关系给用上,也可以正常应对极端不平衡的情况。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * = 297. Serialize and Deserialize Binary Tree
 * <p>
 * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/[Serialize and Deserialize Binary Tree - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-06-16 22:01
 */
class Codec {

  // Encodes a tree to a single string.
  public String serialize(TreeNode root) {
    if (root == null) {
      return "#!";
    }
    String result = root.val + "!";
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
      root = queue.poll();
      if (root.left != null) {
        result += root.left.val + "!";
        queue.offer(root.left);
      } else {
        result += "#!";
      }
      if (root.right != null) {
        result += root.right.val + "!";
        queue.offer(root.right);
      } else {
        result += "#!";
      }
    }
    return result;

  }

  // Decodes your encoded data to tree.
  public TreeNode deserialize(String data) {
    String[] values = data.split("!");
    int index = 0;
    TreeNode head = generate(values[index++]);
    Queue<TreeNode> queue = new LinkedList<>();
    if (head != null) {
      queue.offer(head);
    }
    TreeNode node = null;
    while (!queue.isEmpty()) {
      node = queue.poll();
      node.left = generate(values[index++]);
      node.right = generate(values[index++]);
      if (node.left != null) {
        queue.offer(node.left);
      }
      if (node.right != null) {
        queue.offer(node.right);
      }
    }
    return head;
  }

  private TreeNode generate(String val) {
    if ("#".equals(val)) {
      return null;
    }
    return new TreeNode(Integer.parseInt(val));
  }
}

298. Binary Tree Longest Consecutive Sequence

1
Unresolved directive in 0298-binary-tree-longest-consecutive-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0298_BinaryTreeLongestConsecutiveSequence.java[]

299. Bulls and Cows

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows.

Please note that both secret number and friend’s guess may contain duplicate digits.

Example 1:

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3  cows. The bull is 8 , the cows are 0 , 1  and 7.

Example 2:

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1  is a cow .

*Note: *You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

1
Unresolved directive in 0299-bulls-and-cows.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0299_BullsAndCows.java[]

300. Longest Increasing Subsequence

动态规划+二分查找的算法还需要再仔细研究一下。还是有些懵逼!

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

*Note: *

  • There may be more than one LIS combination, it is only necessary for you to return the length.

  • Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 300. Longest Increasing Subsequence
 *
 * https://leetcode.com/problems/longest-increasing-subsequence/[Longest Increasing Subsequence - LeetCode]
 *
 * Given an unsorted array of integers, find the length of longest increasing subsequence.
 *
 * .Example:
 * [source]
 * ----
 * Input: [10,9,2,5,3,7,101,18]
 * Output: 4
 * Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
 * ----
 *
 * *Note:*
 *
 * * There may be more than one LIS combination, it is only necessary for you to return the length.
 * * Your algorithm should run in O(n^2^) complexity.
 *
 * *Follow up:* Could you improve it to O(n log n) time complexity?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-23 10:24
 */
public class _0300_LongestIncreasingSubsequence {

    /**
     * Runtime: 2 ms, faster than 76.15% of Java online submissions for Longest Increasing Subsequence.
     *
     * Memory Usage: 42.1 MB, less than 5.00% of Java online submissions for Longest Increasing Subsequence.
     *
     * Copy from: https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/zui-chang-shang-sheng-zi-xu-lie-dong-tai-gui-hua-2/[最长上升子序列(动态规划 + 二分查找,清晰图解) - 最长上升子序列 - 力扣(LeetCode)]
     */
    public int lengthOfLIS(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int[] tails = new int[nums.length];
        int result = 0;
        for (int num : nums) {
            int i = 0, j = result;
            while (i < j) {
                int m = (i + j) / 2;
                if (tails[m] < num) {
                    i = m + 1;
                } else {
                    j = m;
                }
            }
            tails[i] = num;
            if (result == j) {
                result++;
            }
        }
        return result;
    }

    /**
     * Runtime: 2 ms, faster than 76.15% of Java online submissions for Longest Increasing Subsequence.
     *
     * Memory Usage: 42.1 MB, less than 5.00% of Java online submissions for Longest Increasing Subsequence.
     *
     * Copy from: https://leetcode.com/problems/longest-increasing-subsequence/solution/[Longest Increasing Subsequence solution - LeetCode]
     */
    public int lengthOfLISDPBS(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        int len = 0;
        for (int num : nums) {
            int i = Arrays.binarySearch(dp, 0, len, num);
            if (i < 0) {
                i = -(i + 1);
            }
            dp[i] = num;
            if (i == len) {
                len++;
            }
        }
        return len;
    }

    /**
     * Runtime: 56 ms, faster than 5.76% of Java online submissions for Longest Increasing Subsequence.
     *
     * Memory Usage: 43.2 MB, less than 5.00% of Java online submissions for Longest Increasing Subsequence.
     *
     * Copy from: https://leetcode.com/problems/longest-increasing-subsequence/solution/[Longest Increasing Subsequence solution - LeetCode]
     */
    public int lengthOfLISDP(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = 1;
        int result = 1;
        for (int i = 1; i < nums.length; i++) {
            int maxval = 0;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    maxval = Math.max(maxval, dp[j]);
                }
            }
            dp[i] = maxval + 1;
            result = Math.max(result, dp[i]);
        }

        return result;
    }

    public static void main(String[] args) {
        _0300_LongestIncreasingSubsequence solution = new _0300_LongestIncreasingSubsequence();
        int[] n1 = {10, 9, 2, 5, 3, 7, 101, 18};
        int r1 = solution.lengthOfLIS(n1);
        System.out.println((r1 == 4) + " : " + r1);
        int[] n2 = {1, 3, 6, 7, 9, 4, 10, 5, 6};
        int r2 = solution.lengthOfLIS(n2);
        System.out.println((r2 == 6) + " : " + r2);

    }
}

301. Remove Invalid Parentheses

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]
1
Unresolved directive in 0301-remove-invalid-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0301_RemoveInvalidParentheses.java[]

302. Smallest Rectangle Enclosing Black Pixels

1
Unresolved directive in 0302-smallest-rectangle-enclosing-black-pixels.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0302_SmallestRectangleEnclosingBlackPixels.java[]

303. Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.

  2. There are many calls to sumRange function.

1
Unresolved directive in 0303-range-sum-query-immutable.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0303_RangeSumQueryImmutable.java[]

304. Range Sum Query 2D - Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (_row_1, _col_1) and lower right corner (_row_2, _col_2).

range sum query 2d

The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note:

  1. You may assume that the matrix does not change.

  2. There are many calls to sumRegion function.

  3. You may assume that _row_1 ≤ _row_2 and _col_1 ≤ _col_2.

1
Unresolved directive in 0304-range-sum-query-2d-immutable.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0304_RangeSumQuery2DImmutable.java[]

305. Number of Islands II

1
Unresolved directive in 0305-number-of-islands-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0305_NumberOfIslandsII.java[]

306. Additive Number

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

Given a string containing only digits '0'-'9', write a function to determine if it’s an additive number.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Example 1:

Input: "112358"
Output: true
Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
             1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

Example 2:

Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
             1 + 99 = 100, 99 + 100 = 199

Constraints:

  • <font face="monospace">`num` consists only of digits '0'-'9'.

  • 1 ⇐ num.length ⇐ 35

Follow up:

How would you handle overflow for very large input integers?

1
Unresolved directive in 0306-additive-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0306_AdditiveNumber.java[]

307. Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.

  2. You may assume the number of calls to update and sumRange function is distributed evenly.

1
Unresolved directive in 0307-range-sum-query-mutable.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0307_RangeSumQueryMutable.java[]

308. Range Sum Query 2D - Mutable

1
Unresolved directive in 0308-range-sum-query-2d-mutable.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0308_RangeSumQuery2DMutable.java[]

309. Best Time to Buy and Sell Stock with Cooldown

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) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]

解题分析

0309 1

这里有一点需要注意:由于卖出后,需要隔一天才能再次买入。所以,需要保存前一天"为空"状态的值。

参考资料

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) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.diguage.algorithm.leetcode;

/**
 * = 309. Best Time to Buy and Sell Stock with Cooldown
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/[Best Time to Buy and Sell Stock with Cooldown - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 15:16
 */
public class _0309_BestTimeToBuyAndSellStockWithCooldown {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Best Time to Buy and Sell Stock with Cooldown.
     * Memory Usage: 37.9 MB, less than 25.93% of Java online submissions for Best Time to Buy and Sell Stock with Cooldown.
     *
     * Copy from: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solution/yi-ge-fang-fa-tuan-mie-6-dao-gu-piao-wen-ti-by-lab/[一个方法团灭 6 道股票问题 - 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)]
     */
    public int maxProfit(int[] prices) {
        int dp0 = 0;
        int dp1 = Integer.MIN_VALUE;
        int last = 0;
        for (int i = 0; i < prices.length; i++) {
            int temp = dp0;
            dp0 = Math.max(dp0, dp1 + prices[i]);
            dp1 = Math.max(dp1, last - prices[i]); // buy 需要基于前一天基础上。
            last = temp;
        }
        return dp0;
    }

    public static void main(String[] args) {
        _0309_BestTimeToBuyAndSellStockWithCooldown solution = new _0309_BestTimeToBuyAndSellStockWithCooldown();
        int[] p1 = {1, 2, 3, 0, 2};
        int r1 = solution.maxProfit(p1);
        System.out.println((r1 == 3) + " : " + r1);
    }
}

310. Minimum Height Trees

For an undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

Format

The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

Example 1 :

Input: n = 4, edges = [[1, 0], [1, 2], [1, 3]]

        0
        |
        1
       / \
      2   3

Output: [1]

Example 2 :

Input: n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
      \ | /
        3
        |
        4
        |
        5

Output: [3, 4]

Note:

  • According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

  • The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

1
Unresolved directive in 0310-minimum-height-trees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0310_MinimumHeightTrees.java[]

311. Sparse Matrix Multiplication

1
Unresolved directive in 0311-sparse-matrix-multiplication.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0311_SparseMatrixMultiplication.java[]

312. Burst Balloons

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.

  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
             coins =  315      +  358    +  138      + 181   = 167
1
Unresolved directive in 0312-burst-balloons.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0312_BurstBalloons.java[]

313. Super Ugly Number

Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.

Example:

Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12
             super ugly numbers given primes = [2,7,13,19] of size 4.

Note:

  • 1 is a super ugly number for any given primes.

  • The given numbers in primes are in ascending order.

  • 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.

  • The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

1
Unresolved directive in 0313-super-ugly-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0313_SuperUglyNumber.java[]

314. Binary Tree Vertical Order Traversal

1
Unresolved directive in 0314-binary-tree-vertical-order-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0314_BinaryTreeVerticalOrderTraversal.java[]

315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Input: [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
1
Unresolved directive in 0315-count-of-smaller-numbers-after-self.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0315_CountOfSmallerNumbersAfterSelf.java[]

316. Remove Duplicate Letters

Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Example 1:

Input: "bcabc"
Output: "abc"

Example 2:

Input: "cbacdcbc"
Output: "acdb"
1
Unresolved directive in 0316-remove-duplicate-letters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0316_RemoveDuplicateLetters.java[]

317. Shortest Distance from All Buildings

1
Unresolved directive in 0317-shortest-distance-from-all-buildings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0317_ShortestDistanceFromAllBuildings.java[]

318. Maximum Product of Word Lengths

Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.

Example 1:

Input: ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".

Example 2:

Input: ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".

Example 3:

Input: ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
1
Unresolved directive in 0318-maximum-product-of-word-lengths.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0318_MaximumProductOfWordLengths.java[]

319. Bulb Switcher

There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it’s off or turning off if it’s on). For the i-th round, you toggle every i bulb. For the n-th round, you only toggle the last bulb. Find how many bulbs are on after n rounds.

Example:

Input: 3
Output: 1
Explanation:
At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off].

So you should return 1, because there is only one bulb is on.
1
Unresolved directive in 0319-bulb-switcher.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0319_BulbSwitcher.java[]

320. Generalized Abbreviation

1
Unresolved directive in 0320-generalized-abbreviation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0320_GeneralizedAbbreviation.java[]

321. Create Maximum Number

Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k ⇐ m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits.

*Note: *You should try to optimize your time and space complexity.

Example 1:

Input:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
Output:
[9, 8, 6, 5, 3]

Example 2:

Input:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
Output:
[6, 7, 6, 0, 4]

Example 3:

Input:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
Output:
[9, 8, 9]
1
Unresolved directive in 0321-create-maximum-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0321_CreateMaximumNumber.java[]

322. Coin Change

0322 1

思考题:

  1. 如何把动态规划代码写得更简洁一些?

  2. 如何使用自底向上方法来实现一遍动态规划?

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:

You may assume that you have an infinite number of each kind of coin.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 322. Coin Change
 *
 * https://leetcode.com/problems/coin-change/[Coin Change - LeetCode]
 *
 * You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return `-1`.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: coins = [1, 2, 5], amount = 11
 * Output: 3
 * Explanation: 11 = 5 + 5 + 1
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: coins = [2], amount = 3
 * Output: -1
 * ----
 *
 * *Note:*
 *
 * You may assume that you have an infinite number of each kind of coin.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 22:16
 */
public class _0322_CoinChange {

    /**
     * Runtime: 91 ms, faster than 6.13% of Java online submissions for Coin Change.
     *
     * Memory Usage: 42.7 MB, less than 5.33% of Java online submissions for Coin Change.
     *
     * Copy from: https://leetcode.com/problems/coin-change/solution/[Coin Change solution - LeetCode]
     */
    public int coinChange(int[] coins, int amount) {
        return coinChange(coins, amount, new int[amount]);
    }

    private int coinChange(int[] coins, int current, int[] count) {
        if (current < 0) {
            return -1;
        }
        if (current == 0) {
            return 0;
        }
        if (count[current - 1] != 0) {
            return count[current - 1];
        }
        int min = Integer.MAX_VALUE;
        for (int coin : coins) {
            int res = coinChange(coins, current - coin, count);
            if (0 <= res && res < min) {
                min = res + 1;
            }
        }
        count[current - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
        return count[current - 1];
    }

    /**
     * Runtime: 427 ms, faster than 5.00% of Java online submissions for Coin Change.
     *
     * Memory Usage: 115.5 MB, less than 5.33% of Java online submissions for Coin Change.
     */
    public int coinChangeDpWithMemo(int[] coins, int amount) {
        int count = dpWithMemo(coins, new HashMap<>(), amount, amount);
        if (count > amount) {
            return -1;
        }
        return count;
    }

    public int dpWithMemo(int[] coins, Map<Integer, Integer> memo, int amount, int current) {
        if (current == 0) {
            return 0;
        }
        if (current < 0) {
            return amount;
        }

        List<Integer> counts = new ArrayList<>();
        for (int coin : coins) {
            int newCoin = current - coin;
            int count;
            if (memo.containsKey(newCoin)) {
                count = memo.get(newCoin);
            } else {
                count = dpWithMemo(coins, memo, amount, newCoin) + 1;
                memo.put(newCoin, count);
            }
            counts.add(count);
        }
        return Collections.min(counts);
    }

    /**
     * Time Limit Exceeded
     */
    public int coinChangeDp(int[] coins, int amount) {
        int count = dp(coins, amount, amount);
        if (count > amount) {
            return -1;
        }
        return count;
    }

    private int dp(int[] coins, int amount, int current) {
        if (current == 0) {
            return 0;
        }
        if (current < 0) {
            return amount;
        }

        List<Integer> counts = new ArrayList<>();
        for (int coin : coins) {
            counts.add(dp(coins, amount, current - coin) + 1);
        }
        return Collections.min(counts);
    }

    public static void main(String[] args) {
        _0322_CoinChange solution = new _0322_CoinChange();
        int[] c1 = {1, 2, 5};
        int r1 = solution.coinChange(c1, 11);
        System.out.println((r1 == 3) + " : " + r1);

        int[] c2 = {2};
        int r2 = solution.coinChange(c2, 3);
        System.out.println((r2 == -1) + " : " + r2);
    }
}

323. Number of Connected Components in an Undirected Graph

1
Unresolved directive in 0323-number-of-connected-components-in-an-undirected-graph.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0323_NumberOfConnectedComponentsInAnUndirectedGraph.java[]

324. Wiggle Sort II

思考题:

  1. 排序再穿插,这个再思考一下?

  2. 找中位数然后索引映射的解法再学习一下。

参考资料

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]…​.

Example 1:

Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].

Note:

You may assume all input has valid answer.

Follow Up:

Can you do it in O(n) time and/or in-place with O(1) extra space?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 324. Wiggle Sort II
 *
 * Given an unsorted array nums, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]....`
 *
 * .Example 1:
 * [source]
 * ----
 * Input: nums = [1, 5, 1, 1, 6, 4]
 * Output: One possible answer is [1, 4, 1, 5, 1, 6].
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [1, 3, 2, 2, 3, 1]
 * Output: One possible answer is [2, 3, 1, 3, 1, 2].
 * ----
 *
 * *Note:*
 *
 * You may assume all input has valid answer.
 *
 * *Follow Up:*
 *
 * Can you do it in O(n) time and/or in-place with O(1) extra space?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 23:29
 */
public class _0324_WiggleSortII {

    /**
     * Runtime: 3 ms, faster than 99.88% of Java online submissions for Wiggle Sort II.
     *
     * Memory Usage: 44.2 MB, less than 10.00% of Java online submissions for Wiggle Sort II.
     *
     * Copy from https://leetcode-cn.com/problems/wiggle-sort-ii/solution/javaxiang-xi-ti-jie-shuo-ming-by-heator/[Java详细题解说明 - 摆动排序 II - 力扣(LeetCode)]
     */
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        int length = nums.length;
        int[] smaller = new int[length % 2 == 0 ? length / 2 : (length / 2 + 1)];
        int[] bigger = new int[length / 2];
        System.arraycopy(nums, 0, smaller, 0, smaller.length);
        System.arraycopy(nums, smaller.length, bigger, 0, bigger.length);
        int i = 0;
        for (; i < length / 2; i++) {
            int si = smaller.length - 1 - i;
            nums[2 * i] = smaller[si];
            int bi = length / 2 - 1 - i;
            nums[2 * i + 1] = bigger[bi];
        }
        if (length % 2 != 0) {
            nums[2 * i] = smaller[smaller.length - 1 - i];
        }
    }


    public static void main(String[] args) {
        _0324_WiggleSortII solution = new _0324_WiggleSortII();
        int[] n1 = {1, 5, 1, 1, 6, 4};
        solution.wiggleSort(n1);
        System.out.println(Arrays.toString(n1));

        int[] n2 = {1, 3, 2, 2, 3, 1};
        solution.wiggleSort(n2);
        System.out.println(Arrays.toString(n2));
    }
}

325. Maximum Size Subarray Sum Equals k

1
Unresolved directive in 0325-maximum-size-subarray-sum-equals-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0325_MaximumSizeSubarraySumEqualsK.java[]

326. Power of Three

发现一个很奇怪的问题:如果通过计算相乘来判断,则会超时;如果通过相除来判断,则能顺利通过。感觉计算量是一样的啊?为什会有这么大的差距啊?

利用对数计算也不失为一个很好的办法!

Given an integer, write a function to determine if it is a power of three.

Example 1:

Input: 27
Output: true

Example 2:

Input: 0
Output: false

Example 3:

Input: 9
Output: true

Example 4:

Input: 45
Output: false

Follow up:

Could you do it without using any loop / recursion?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.diguage.algorithm.leetcode;

/**
 * = 326. Power of Three
 *
 * https://leetcode.com/problems/power-of-three/[Power of Three - LeetCode]
 *
 * Given an integer, write a function to determine if it is a power of three.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: 27
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 0
 * Output: false
 * ----
 *
 * .Example 3:
 * [source]
 * ----
 * Input: 9
 * Output: true
 * ----
 *
 * .Example 4:
 * [source]
 * ----
 * Input: 45
 * Output: false
 * ----
 *
 * Follow up:
 * Could you do it without using any loop / recursion?
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-14 22:54
 */
public class _0326_PowerOfThree {
    /**
     * Runtime: 11 ms, faster than 89.24% of Java online submissions for Power of Three.
     *
     * Memory Usage: 36.4 MB, less than 6.25% of Java online submissions for Power of Three.
     *
     * Copy from: https://leetcode.com/problems/power-of-three/solution/[Power of Three solution - LeetCode]
     */
    public boolean isPowerOfThree(int n) {
        return (Math.log10(n) / Math.log10(3)) % 1 == 0;
    }
    /**
     * Runtime: 11 ms, faster than 89.24% of Java online submissions for Power of Three.
     *
     * Memory Usage: 36.6 MB, less than 6.25% of Java online submissions for Power of Three.
     *
     * Copy from: https://leetcode.com/problems/power-of-three/solution/[Power of Three solution - LeetCode]
     */
    public boolean isPowerOfThreeDiv(int n) {
        if (n < 1) {
            return false;
        }
        while (n % 3 == 0) {
            n /= 3;
        }
        return n == 1;
    }

    /**
     * Time Limit Exceeded
     */
    public boolean isPowerOfThreeMult(int n) {
        if (n < 1) {
            return false;
        }
        int temp = 1;
        for (int i = 0; temp <= n && i < n; i++) {
            if (temp == n) {
                return true;
            }
            temp *= 3;
        }
        return false;
    }

    public static void main(String[] args) {
        _0326_PowerOfThree solution = new _0326_PowerOfThree();
        System.out.println(solution.isPowerOfThree(2147483647));
        System.out.println(solution.isPowerOfThree(45));
        System.out.println(solution.isPowerOfThree(81));
    }
}

327. Count of Range Sum

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive.

Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (ij), inclusive.

Note:

A naive algorithm of O(n2) is trivial. You MUST do better than that.

Example:

Input: nums = [-2,5,-1], lower = -2, upper = 2,
Output: 3
Explanation: The three ranges are : [0,0], [2,2], [0,2] and their respective sums are: -2, -1, 2.
1
Unresolved directive in 0327-count-of-range-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0327_CountOfRangeSum.java[]

328. Odd Even Linked List

使用双指针,将链表拆分成奇偶数两个链表,然后再拼接!确实是个很棒的方法!

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL

Note:

  • The relative order inside both the even and odd groups should remain as it was in the input.

  • The first node is considered odd, the second node even and so on …​

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.ListNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.ListNodeUtils.build;
import static com.diguage.algorithm.util.ListNodeUtils.printListNode;

/**
 * = 328. Odd Even Linked List
 *
 * https://leetcode.com/problems/odd-even-linked-list/[Odd Even Linked List - LeetCode]
 *
 * Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
 *
 * You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 1->2->3->4->5->NULL
 * Output: 1->3->5->2->4->NULL
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: 2->1->3->5->6->4->7->NULL
 * Output: 2->3->6->7->1->5->4->NULL
 * ----
 *
 * *Note:*
 *
 * * The relative order inside both the even and odd groups should remain as it was in the input.
 * * The first node is considered odd, the second node even and so on ...
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-12 12:20
 */
public class _0328_OddEvenLinkedList {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Odd Even Linked List.
     *
     * Memory Usage: 38 MB, less than 12.50% of Java online submissions for Odd Even Linked List.
     *
     * Copy from: https://leetcode.com/problems/odd-even-linked-list/solution/[Odd Even Linked List solution - LeetCode]
     */
    public ListNode oddEvenList(ListNode head) {
        if (Objects.isNull(head)) {
            return null;
        }
        ListNode odd = head;
        ListNode even = head.next;
        ListNode evenHead = even;
        while (Objects.nonNull(even) && Objects.nonNull(even.next)) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }

    public static void main(String[] args) {
        _0328_OddEvenLinkedList solution = new _0328_OddEvenLinkedList();
        ListNode r1 = solution.oddEvenList(build(Arrays.asList(1, 2, 3, 4, 5)));
        printListNode(r1);
    }
}

329. Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example 1:

Input: nums =
[
  [<font color="red">9,9,4],
  [<font color="red">6,6,8],
  [<font color="red">2,<font color="red">1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: nums =
[
  [<font color="red">3,<font color="red">4,<font color="red">5],
  [3,2,<font color="red">6],
  [2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
1
Unresolved directive in 0329-longest-increasing-path-in-a-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0329_LongestIncreasingPathInAMatrix.java[]

330. Patching Array

Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.

Example 1:

Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.

Example 2:

Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].

Example 3:

Input: nums = [1,2,2], n = 5
Output: 0
1
Unresolved directive in 0330-patching-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0330_PatchingArray.java[]

331. Verify Preorder Serialization of a Binary Tree

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as #.

     9
    /   \
   3     2
  / \   / \
 4   1    6
/ \ / \   / \
       #

For example, the above binary tree can be serialized to the string "9,3,4,,,1,,,2,,6,,", where represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character '#' representing null pointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".

Example 1:

Input: "9,3,4,,,1,,,2,,6,,#"
Output: true

Example 2:

Input: "1,#"
Output: false

Example 3:

Input: "9,,,1"
Output: false
1
Unresolved directive in 0331-verify-preorder-serialization-of-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0331_VerifyPreorderSerializationOfABinaryTree.java[]

332. Reconstruct Itinerary

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:

  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

  2. All airports are represented by three capital letters (IATA code).

  3. You may assume all tickets form at least one valid itinerary.

Example 1:

Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
             But it is larger in lexical order.
1
Unresolved directive in 0332-reconstruct-itinerary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0332_ReconstructItinerary.java[]

333. Largest BST Subtree

1
Unresolved directive in 0333-largest-bst-subtree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0333_LargestBSTSubtree.java[]

334. Increasing Triplet Subsequence

更优的解题思路:

首先,新建两个变量 small 和 mid ,分别用来保存题目要我们求的长度为 3 的递增子序列的最小值和中间值。

接着,我们遍历数组,每遇到一个数字,我们将它和 small 和 mid 相比,若小于等于 small ,则替换 small;否则,若小于等于 mid,则替换 mid;否则,若大于 mid,则说明我们找到了长度为 3 的递增数组!

上面的求解过程中有个问题:当已经找到了长度为 2 的递增序列,这时又来了一个比 small 还小的数字,为什么可以直接替换 small 呢,这样 small 和 mid 在原数组中并不是按照索引递增的关系呀?

Trick 就在这里了!假如当前的 small 和 mid 为 [3, 5],这时又来了个 1。假如我们不将 small 替换为 1,那么,当下一个数字是 2,后面再接上一个 3 的时候,我们就没有办法发现这个 [1,2,3] 的递增数组了!也就是说,我们替换最小值,是为了后续能够更好地更新中间值!

另外,即使我们更新了 small ,这个 small 在 mid 后面,没有严格遵守递增顺序,但它隐含着的真相是,有一个比 small 大比 mid 小的前·最小值出现在 mid 之前。因此,当后续出现比 mid 大的值的时候,我们一样可以通过当前 small 和 mid 推断的确存在着长度为 3 的递增序列。 所以,这样的替换并不会干扰我们后续的计算!

参考资料

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:

<blockquote>Return true if there exists _i, j, k _

such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < kn-1 else return false.</blockquote>

*Note: *Your algorithm should run in O(n) time complexity and O(1) space complexity.

Example 1:

Input: [1,2,3,4,5]
Output: true

Example 2:

Input: [5,4,3,2,1]
Output: false
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * = 334. Increasing Triplet Subsequence
 *
 * Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
 *
 * Formally the function should:
 *
 * ****
 * Return true if there exists i, j, k
 * such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
 * ****
 *
 * *Note:* Your algorithm should run in O(n) time complexity and O(1) space complexity.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: [1,2,3,4,5]
 * Output: true
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: [5,4,3,2,1]
 * Output: false
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 14:26
 */
public class _0334_IncreasingTripletSubsequence {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Increasing Triplet Subsequence.
     *
     * Memory Usage: 39.3 MB, less than 93.02% of Java online submissions for Increasing Triplet Subsequence.
     */
    public boolean increasingTriplet(int[] nums) {
        if (Objects.isNull(nums) || nums.length < 3) {
            return false;
        }
        int small = Integer.MAX_VALUE;
        int mid = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (num <= small) {
                small = num;
            } else if (num <= mid) {
                mid = num;
            } else if (mid < num) {
                return true;
            }
        }
        return false;
    }

    /**
     * Runtime: 152 ms, faster than 5.23% of Java online submissions for Increasing Triplet Subsequence.
     *
     * Memory Usage: 40.4 MB, less than 6.98% of Java online submissions for Increasing Triplet Subsequence.
     */
    public boolean increasingTripletDp(int[] nums) {
        if (Objects.isNull(nums) || nums.length < 3) {
            return false;
        }
        int[] dp = new int[nums.length];
        Arrays.fill(dp, 1);
        int max = 1;
        for (int i = 1; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            max = Math.max(max, dp[i]);
            if (max >= 3) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        _0334_IncreasingTripletSubsequence solution = new _0334_IncreasingTripletSubsequence();

        int[] n5 = {1, 1, -2, 6};
        boolean r5 = solution.increasingTriplet(n5);
        System.out.println(!r5);


        int[] n4 = {2, 4, -2, -3};
        boolean r4 = solution.increasingTriplet(n4);
        System.out.println(!r4);

        int[] n3 = {1, 2, 3, 1, 2, 1};
        boolean r3 = solution.increasingTriplet(n3);
        System.out.println(r3);

        int[] n1 = {1, 2, 3, 4, 5};
        boolean r1 = solution.increasingTriplet(n1);
        System.out.println(r1);

        int[] n2 = {5, 4, 3, 2, 1};
        boolean r2 = solution.increasingTriplet(n2);
        System.out.println(!r2);
    }
}

335. Self Crossing

You are given an array x of n positive numbers. You start at point (0,0) and moves x[0] metres to the north, then x[1] metres to the west, x[2] metres to the south, x[3] metres to the east and so on. In other words, after each move your direction changes counter-clockwise.

Write a one-pass algorithm with O(1) extra space to determine, if your path crosses itself, or not.

Example 1:

┌───┐
   
└───┼──>
    

Input: [2,1,1,2]
Output: true

Example 2:

┌──────┐
      


└────────────>

Input: [1,2,3,4]
Output: false

Example 3:

┌───┐
   
└───┼>

Input: [1,1,1,1]
Output: true
1
Unresolved directive in 0335-self-crossing.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0335_SelfCrossing.java[]

336. Palindrome Pairs

Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Example 1:

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2:

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
1
Unresolved directive in 0336-palindrome-pairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0336_PalindromePairs.java[]

337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:
Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \
     3   1

Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

解题分析

由于题目给出示例的误导,这里存在一个误区:在不选父节点时,子树选最优解不受任何干扰,也就是说子树的跟节点可选也可以不选。所以,可以将这个问题简化为,分选根节点和不选根节点,两种情况考虑:

  1. 选父节点,则子树必定不能选根节点;

  2. 如果不选跟节点,则子树可以在选根节点和不选跟节点中选最优解就好。

然后在这上面两种情况中选出最优解。

思考题

尝试使用动态规划来解决这个问题。

参考资料

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \
     3   1

Output: 7
Explanation: Maximum amount of money the thief can rob = <font color="red" style="font-family: sans-serif, Arial, Verdana, "Trebuchet MS";">3 + <font color="red" style="font-family: sans-serif, Arial, Verdana, "Trebuchet MS";">3  + <font color="red" style="font-family: sans-serif, Arial, Verdana, "Trebuchet MS";">1  = <b style="font-family: sans-serif, Arial, Verdana, "Trebuchet MS";">7* .

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + <font color="red">5 = 9.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 337. House Robber III
 *
 * https://leetcode.com/problems/house-robber-iii/[House Robber III - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 16:34
 */
public class _0337_HouseRobberIII {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for House Robber III.
     * Memory Usage: 41.3 MB, less than 13.89% of Java online submissions for House Robber III.
     *
     * Copy from: https://leetcode-cn.com/problems/house-robber-iii/solution/java-2ms-by-horanol/[java 2ms - 打家劫舍 III - 力扣(LeetCode)]
     */
    public int rob(TreeNode root) {
        int[] robs = doRob(root);
        return Math.max(robs[0], robs[1]);
    }

    public int[] doRob(TreeNode root) {
        int[] result = new int[2];
        if (Objects.isNull(root)) {
            return result;
        }
        int[] left = doRob(root.left);
        int[] right = doRob(root.right);
        result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        result[1] = left[0] + right[0] + root.val;
        return result;
    }

    public static void main(String[] args) {
        _0337_HouseRobberIII solution = new _0337_HouseRobberIII();
        int r1 = solution.rob(buildTree(asList(3, 2, 3, null, 3, null, 1)));
        System.out.println((r1 == 7) + " : " + r1);

        int r2 = solution.rob(buildTree(asList(3, 4, 5, 1, 3, null, 1)));
        System.out.println((r2 == 9) + " : " + r2);
    }
}

338. Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?

  • Space complexity should be O(n).

  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

解题分析

0 开始,每个奇数包含 1 的个数,都比前面一个数要多 1。所以,只需要计算偶数包含的 1 的个数,然后奇数直接在前面的基础上加 1 即可。

另外一种解法:以 2x 次幂为界,后面的的 x 个数中的 1 的个数,是前面个 x 个数在前面加 1 的结果(位数不够在前面补零,例如从 15,就是从 1 补零 001,再前面加 1,则为 1001)。

\begin{aligned} (0)&=(0)_{2}\\ (1)&=(1)_{2}\\ (2)&=(10)_{2}\\ (3)&=(11)_{2}\\ P(x+b)&=P(x)+1, b=2^{m}>x\\ \end{aligned}

for (int i = 0; i < 99; i++) {
    int j = 0;
    for (; Math.pow(2, j) <= i; j++) {
        if (Math.pow(2, j) == i && i != 1) {
            System.out.println("---");
        }
    }
    System.out.printf("%2d  %10s\n", i, Integer.toBinaryString(i));
}

用这段代码输出一下,观察一下更明显。

这个题的解法跟 89. Gray Code 有异曲同工之妙!

思考题:尝试"动态规划 + 最低有效位"的解法。

参考资料

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?

  • Space complexity should be O(n).

  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.diguage.algorithm.leetcode;

import java.util.Arrays;

/**
 * = 338. Counting Bits
 * <p>
 * https://leetcode.com/problems/counting-bits/[Counting Bits - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 14:50
 */
public class _0338_CountingBits {
    /**
     * Runtime: 1 ms, faster than 99.73% of Java online submissions for Counting Bits.
     * Memory Usage: 43 MB, less than 5.88% of Java online submissions for Counting Bits.
     * <p>
     * Copy from: https://leetcode-cn.com/problems/counting-bits/solution/bi-te-wei-ji-shu-by-leetcode/[比特位计数 - 比特位计数 - 力扣(LeetCode)]
     */
    public int[] countBits(int num) {
        int[] result = new int[num + 1];
        int b = 1;
        int i = 0;
        while (b <= num) {
            while (i < b && i + b <= num) {
                result[i + b] = result[i] + 1;
                ++i;
            }
            i = 0;
            b <<= 1;
        }
        return result;
    }

    /**
     * Runtime: 3 ms, faster than 24.83% of Java online submissions for Counting Bits.
     * Memory Usage: 43 MB, less than 5.88% of Java online submissions for Counting Bits.
     */
    public int[] countBitsEvenOdd(int num) {
        int[] result = new int[num + 1];
        for (int i = 0; i <= num; i += 2) {
            result[i] = bitsInNum(i);
        }
        for (int i = 1; i <= num; i += 2) {
            result[i] = result[i - 1] + 1;
        }
        return result;
    }

    private int bitsInNum(int num) {
        int result = 0;
        while (num != 0) {
            if ((num & 1) == 1) {
                result++;
            }
            num = num >>> 1;
        }
        return result;
    }

    public static void main(String[] args) {
        _0338_CountingBits solution = new _0338_CountingBits();
        System.out.println(Arrays.toString(solution.countBits(2)));
        System.out.println(Arrays.toString(solution.countBits(5)));
        System.out.println(Arrays.toString(solution.countBits(10)));

for (int i = 0; i < 99; i++) {
    int j = 0;
    for (; Math.pow(2, j) <= i; j++) {
        if (Math.pow(2, j) == i && i != 1) {
            System.out.println("---");
        }
    }
    System.out.printf("%2d  %10s\n", i, Integer.toBinaryString(i));
}
    }
}

339. Nested List Weight Sum

1
Unresolved directive in 0339-nested-list-weight-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0339_NestedListWeightSum.java[]

340. Longest Substring with At Most K Distinct Characters

1
Unresolved directive in 0340-longest-substring-with-at-most-k-distinct-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0340_LongestSubstringWithAtMostKDistinctCharacters.java[]

341. Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list — whose elements may also be integers or other lists.

Example 1:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,4,6].

思考题:这道题还可以使用栈来实现。尝试一下。

参考资料

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list — whose elements may also be integers or other lists.

Example 1:

Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,1,2,1,1].

Example 2:

Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
             the order of elements returned by next should be: [1,4,6].
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 341. Flatten Nested List Iterator
 *
 * https://leetcode.com/problems/flatten-nested-list-iterator/[Flatten Nested List Iterator - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 15:17
 */
public class _0341_FlattenNestedListIterator {
    public interface NestedInteger {

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger();

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        public List<NestedInteger> getList();
    }

    /**
     * Runtime: 2 ms, faster than 99.89% of Java online submissions for Flatten Nested List Iterator.
     *
     * Memory Usage: 42.9 MB, less than 5.00% of Java online submissions for Flatten Nested List Iterator.
     */
    public class NestedIterator implements Iterator<Integer> {
        private Queue<Integer> queue;

        public NestedIterator(List<NestedInteger> nestedList) {
            queue = new LinkedList<>();
            dfs(nestedList);
        }

        private void dfs(List<NestedInteger> nestedList) {
            if (Objects.isNull(nestedList) || nestedList.isEmpty()) {
                return;
            }

            for (NestedInteger nestedInteger : nestedList) {
                if (nestedInteger.isInteger()) {
                    queue.offer(nestedInteger.getInteger());
                } else {
                    dfs(nestedInteger.getList());
                }
            }
        }

        @Override
        public Integer next() {
            return queue.poll();
        }

        @Override
        public boolean hasNext() {
            return !queue.isEmpty();
        }
    }

    private void test() {
        List<NestedInteger> nestedList = new ArrayList<>();
        NestedIterator iterator = new NestedIterator(nestedList);
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    public static void main(String[] args) {
        _0341_FlattenNestedListIterator solution = new _0341_FlattenNestedListIterator();
        solution.test();
    }
}

342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false

Follow up: Could you solve it without loops/recursion?

1
Unresolved directive in 0342-power-of-four.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0342_PowerOfFour.java[]

343. Integer Break

Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

Example 1:

Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 &times; 1 = 1.

Example 2:

Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36.

Note: You may assume that n is not less than 2 and not larger than 58.

解题分析

0343 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.diguage.algorithm.leetcode;

/**
 * = 343. Integer Break
 * <p>
 * https://leetcode.com/problems/integer-break/[Integer Break - LeetCode^]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-26 16:38
 */
public class _0343_IntegerBreak {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Integer Break.
     * Memory Usage: 38.1 MB, less than 14.29% of Java online submissions for Integer Break.
     *
     * Copy from: https://leetcode-cn.com/problems/jian-sheng-zi-lcof/solution/mian-shi-ti-14-i-jian-sheng-zi-tan-xin-si-xiang-by/[面试题14- I. 剪绳子(数学推导 / 贪心思想,清晰图解) - 剪绳子 - 力扣(LeetCode)]
     */
    public int integerBreak(int n) {
        if (n < 2) {
            return 0;
        }
        if (n == 2) {
            return 1;
        }
        if (n == 3) {
            return 2;
        }
        int timeOf3 = n / 3;
        int mod = n % 3;
        if (mod == 0) {
            return (int) Math.pow(3, timeOf3);
        }
        if (mod == 1) {
            return (int) Math.pow(3, timeOf3 - 1) * (3 + 1);
        }
        return (int) Math.pow(3, timeOf3) * 2;
    }

    public static void main(String[] args) {
        _0343_IntegerBreak solution = new _0343_IntegerBreak();
        System.out.println(solution.integerBreak(10));
    }
}

344. Reverse String

这个跟 Valid Palindrome - LeetCode 的思路类似,都是"左右夹击"。

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 344. Reverse String
 *
 * https://leetcode.com/problems/reverse-string/[Reverse String - LeetCode]
 *
 * Write a function that reverses a string. The input string is given as an array of characters char[].
 *
 * Do not allocate extra space for another array, you must do this by *modifying the input array* in-place with O(1) extra memory.
 *
 * You may assume all the characters consist of printable ascii characters.
 *
 * .Example 2:
 * [source]
 * ----
 * Input: ["h","e","l","l","o"]
 * Output: ["o","l","l","e","h"]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: ["H","a","n","n","a","h"]
 * Output: ["h","a","n","n","a","H"]\
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-15 00:03
 */
public class _0344_ReverseString {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse String.
     *
     * Memory Usage: 52.7 MB, less than 5.33% of Java online submissions for Reverse String.
     */
    public void reverseString(char[] s) {
        if (Objects.isNull(s) || s.length == 0) {
            return;
        }
        for (int left = 0, right = s.length - 1; left < right; left++, right--) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
        }
    }

    public static void main(String[] args) {
        _0344_ReverseString solution = new _0344_ReverseString();
        char[] c1 = "hello".toCharArray();
        solution.reverseString(c1);
        System.out.println(new String(c1));
    }
}

345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note:

The vowels does not include the letter "y".

1
Unresolved directive in 0345-reverse-vowels-of-a-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0345_ReverseVowelsOfAString.java[]

346. Moving Average from Data Stream

1
Unresolved directive in 0346-moving-average-from-data-stream.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0346_MovingAverageFromDataStream.java[]

347. Top K Frequent Elements

利用桶排序实在是妙妙妙啊!

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

*Note: *

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

  • Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 347. Top K Frequent Elements
 *
 * https://leetcode.com/problems/top-k-frequent-elements/[Top K Frequent Elements - LeetCode]
 *
 * Given a non-empty array of integers, return the `k` most frequent elements.
 *
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [1,1,1,2,2,3], k = 2
 * Output: [1,2]
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: nums = [1], k = 1
 * Output: [1]
 * ----
 *
 * *Note:*
 *
 * * You may assume `k` is always valid, `1 ≤ k ≤ number` of unique elements.
 * * Your algorithm's time complexity *must be* better than O(nlogn), where `n` is the array's size.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-11 00:04
 */
public class _0347_TopKFrequentElements {
    /**
     * Runtime: 10 ms, faster than 98.24% of Java online submissions for Top K Frequent Elements.
     *
     * Memory Usage: 41.2 MB, less than 31.89% of Java online submissions for Top K Frequent Elements.
     *
     * Copy from: https://leetcode.com/problems/top-k-frequent-elements/discuss/81602/Java-O(n)-Solution-Bucket-Sort[Java O(n) Solution - Bucket Sort - LeetCode Discuss]
     */
    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> numToCountMap = new HashMap<>();
        for (int num : nums) {
            Integer count = numToCountMap.getOrDefault(num, 0);
            numToCountMap.put(num, ++count);
        }
        List<Integer>[] bucket = new List[nums.length + 1];
        for (Map.Entry<Integer, Integer> entry : numToCountMap.entrySet()) {
            if (Objects.isNull(bucket[entry.getValue()])) {
                bucket[entry.getValue()] = new ArrayList<>();
            }
            bucket[entry.getValue()].add(entry.getKey());
        }
        List<Integer> result = new ArrayList<>(k);
        for (int i = bucket.length - 1; i >= 0 && result.size() < k; i--) {
            if (Objects.nonNull(bucket[i])) {
                result.addAll(bucket[i]);
            }
        }
        return result;
    }

    /**
     * Runtime: 12 ms, faster than 81.45% of Java online submissions for Top K Frequent Elements.
     *
     * Memory Usage: 40.3 MB, less than 69.83% of Java online submissions for Top K Frequent Elements.
     */
    public List<Integer> topKFrequentSort(int[] nums, int k) {
        Map<Integer, Integer> numToCountMap = new HashMap<>();
        for (int num : nums) {
            Integer count = numToCountMap.getOrDefault(num, 0);
            numToCountMap.put(num, ++count);
        }
        List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(numToCountMap.entrySet());
        entries.sort((e1, e2) -> e2.getValue() - e1.getValue());
        List<Integer> result = new ArrayList<>(k);
        for (int i = 0; i < k; i++) {
            result.add(entries.get(i).getKey());
        }
        return result;
    }

    public static void main(String[] args) {
        _0347_TopKFrequentElements solution = new _0347_TopKFrequentElements();
        List<Integer> r1 = solution.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2);
        System.out.println(Arrays.toString(r1.toArray()));
    }
}

348. Design Tic-Tac-Toe

1
Unresolved directive in 0348-design-tic-tac-toe.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0348_DesignTicTacToe.java[]

349. Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.

  • The result can be in any order.

1
Unresolved directive in 0349-intersection-of-two-arrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0349_IntersectionOfTwoArrays.java[]

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.

  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?

  • What if nums1's size is small compared to nums2's size? Which algorithm is better?

  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

1
Unresolved directive in 0350-intersection-of-two-arrays-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0350_IntersectionOfTwoArraysII.java[]

351. Android Unlock Patterns

1
Unresolved directive in 0351-android-unlock-patterns.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0351_AndroidUnlockPatterns.java[]

352. Data Stream as Disjoint Intervals

Given a data stream input of non-negative integers a1, a2, …​, an, …​, summarize the numbers seen so far as a list of disjoint intervals.

For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, …​, then the summary will be:

[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]

Follow up:

What if there are lots of merges and the number of disjoint intervals are small compared to the data stream’s size?

1
Unresolved directive in 0352-data-stream-as-disjoint-intervals.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0352_DataStreamAsDisjointIntervals.java[]

353. Design Snake Game

1
Unresolved directive in 0353-design-snake-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0353_DesignSnakeGame.java[]

354. Russian Doll Envelopes

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Note:

Rotation is not allowed.

Example:

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
1
Unresolved directive in 0354-russian-doll-envelopes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0354_RussianDollEnvelopes.java[]

355. Design Twitter

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user’s news feed. Your design should support the following methods:

  1. postTweet(userId, tweetId): Compose a new tweet.

  2. getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the user’s news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.

  3. follow(followerId, followeeId): Follower follows a followee.

  4. unfollow(followerId, followeeId): Follower unfollows a followee.

Example:

Twitter twitter = new Twitter();

// User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);

// User 1 follows user 2.
twitter.follow(1, 2);

// User 2 posts a new tweet (id = 6).
twitter.postTweet(2, 6);

// User 1's news feed should return a list with 2 tweet ids -> [6, 5].
// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.getNewsFeed(1);

// User 1 unfollows user 2.
twitter.unfollow(1, 2);

// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);
1
Unresolved directive in 0355-design-twitter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0355_DesignTwitter.java[]

356. Line Reflection

1
Unresolved directive in 0356-line-reflection.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0356_LineReflection.java[]

357. Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:

Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0  x < 100,
             excluding 11,22,33,44,55,66,77,88,99
1
Unresolved directive in 0357-count-numbers-with-unique-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0357_CountNumbersWithUniqueDigits.java[]

358. Rearrange String k Distance Apart

1
Unresolved directive in 0358-rearrange-string-k-distance-apart.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0358_RearrangeStringKDistanceApart.java[]

359. Logger Rate Limiter

1
Unresolved directive in 0359-logger-rate-limiter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0359_LoggerRateLimiter.java[]

360. Sort Transformed Array

1
Unresolved directive in 0360-sort-transformed-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0360_SortTransformedArray.java[]

361. Bomb Enemy

1
Unresolved directive in 0361-bomb-enemy.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0361_BombEnemy.java[]

362. Design Hit Counter

1
Unresolved directive in 0362-design-hit-counter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0362_DesignHitCounter.java[]

363. Max Sum of Rectangle No Larger Than K

Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.

Example:

Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of rectangle [[0, 1], [-2, 3]] is 2,
             and 2 is the max number no larger than k (k = 2).

Note:

  1. The rectangle inside the matrix must have an area > 0.

  2. What if the number of rows is much larger than the number of columns?

1
Unresolved directive in 0363-max-sum-of-rectangle-no-larger-than-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0363_MaxSumOfRectangleNoLargerThanK.java[]

364. Nested List Weight Sum II

1
Unresolved directive in 0364-nested-list-weight-sum-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0364_NestedListWeightSumII.java[]

365. Water and Jug Problem

You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.

Operations allowed:

  • Fill any of the jugs completely with water.

  • Empty any of the jugs.

  • Pour water from one jug into another till the other jug is completely full or the first jug itself is empty.

Example 1: (From the famous "Die Hard" example)

Input: x = 3, y = 5, z = 4
Output: True

Example 2:

Input: x = 2, y = 6, z = 5
Output: False
1
Unresolved directive in 0365-water-and-jug-problem.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0365_WaterAndJugProblem.java[]

366. Find Leaves of Binary Tree

1
Unresolved directive in 0366-find-leaves-of-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0366_FindLeavesOfBinaryTree.java[]

367. Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Output: true

Example 2:

Input: 14
Output: false
1
Unresolved directive in 0367-valid-perfect-square.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0367_ValidPerfectSquare.java[]

368. Largest Divisible Subset

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:

Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)

Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]
1
Unresolved directive in 0368-largest-divisible-subset.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0368_LargestDivisibleSubset.java[]

369. Plus One Linked List

1
Unresolved directive in 0369-plus-one-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0369_PlusOneLinkedList.java[]

370. Range Addition

1
Unresolved directive in 0370-range-addition.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0370_RangeAddition.java[]

371. Sum of Two Integers

这道题的关键有几点:

  1. 通过异或操作获取在不进位的情况下,各位的值;

  2. 通过相与加移位来来获取各个进位项;

  3. 重复上面的操作,直到进位项为 0 为止。

思考题:思考如何通过位运算来实现加减乘除?

参考资料

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

Input: a = 1, b = 2
Output: 3

Example 2:

Input: a = -2, b = 3
Output: 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.diguage.algorithm.leetcode;

/**
 * = 371. Sum of Two Integers
 *
 * https://leetcode.com/problems/sum-of-two-integers/[Sum of Two Integers - LeetCode]
 *
 * Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
 *
 * .Example 1:
 * [source]
 * ----
 * Input: a = 1, b = 2
 * Output: 3
 * ----
 *
 * .Example 2:
 * [source]
 * ----
 * Input: a = -2, b = 3
 * Output: 1
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-25 17:03
 */
public class _0371_SumOfTwoIntegers {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Two Integers.
     *
     * Memory Usage: 37.9 MB, less than 6.67% of Java online submissions for Sum of Two Integers.
     */
    public int getSumLoop(int a, int b) {
        while (b != 0) {
            int temp = a ^ b;
            b = (a & b) << 1;
            a = temp;
        }
        return a;
    }

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Two Integers.
     *
     * Memory Usage: 37.7 MB, less than 6.67% of Java online submissions for Sum of Two Integers.
     */
    public int getSum(int a, int b) {
        return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
    }

    public static void main(String[] args) {
        _0371_SumOfTwoIntegers solution = new _0371_SumOfTwoIntegers();
        int r1 = solution.getSum(1, 2);
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.getSum(29, 23);
        System.out.println((r2 == 52) + " : " + r2);
    }
}

372. Super Pow

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

Example 1:

Input: a = 2, b = [3]
Output: 8

Example 2:

Input: a = 2, b = [1,0]
Output: 1024
1
Unresolved directive in 0372-super-pow.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0372_SuperPow.java[]

373. Find K Pairs with Smallest Sums

You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.

Define a pair (u,v) which consists of one element from the first array and one element from the second array.

Find the k pairs (u1,v1),(u2,v2) …​(uk,vk) with the smallest sums.

Example 1:

Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Output: [[1,2],[1,4],[1,6]]
Explanation: The first 3 pairs are returned from the sequence:
             [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]

Example 2:

Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Output: [1,1],[1,1]
Explanation: The first 2 pairs are returned from the sequence:
             [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]

Example 3:

Input: nums1 = [1,2], nums2 = [3], k = 3
Output: [1,3],[2,3]
Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
1
Unresolved directive in 0373-find-k-pairs-with-smallest-sums.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0373_FindKPairsWithSmallestSums.java[]

374. Guess Number Higher or Lower

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I’ll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example :

Input: n = 10, pick = 6
Output: 6
1
Unresolved directive in 0374-guess-number-higher-or-lower.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0374_GuessNumberHigherOrLower.java[]

375. Guess Number Higher or Lower II

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I’ll tell you whether the number I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Example:

n = 10, I pick 8.

First round:  You guess 5, I tell you that it's higher. You pay $5.
Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round:  You guess 9, I tell you that it's lower. You pay $9.

Game over. 8 is the number I picked.

You end up paying $5 + $7 + $9 = $21.

Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.

1
Unresolved directive in 0375-guess-number-higher-or-lower-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0375_GuessNumberHigherOrLowerII.java[]

376. Wiggle Subsequence

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.

For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.

Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.

Example 1:

Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.

Example 2:

Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

Example 3:

Input: [1,2,3,4,5,6,7,8,9]
Output: 2

Follow up:

Can you do it in O(n) time?

1
Unresolved directive in 0376-wiggle-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0376_WiggleSubsequence.java[]

377. Combination Sum IV

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

Follow up:

What if negative numbers are allowed in the given array?

How does it change the problem?

What limitation we need to add to the question to allow negative numbers?

Credits:

Special thanks to <a href="https://leetcode.com/pbrother/">@pbrother</a> for adding this problem and creating all test cases.

1
Unresolved directive in 0377-combination-sum-iv.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0377_CombinationSumIV.java[]

378. Kth Smallest Element in a Sorted Matrix

这里还是要注意一下:从右上角向左移,从上向下移,可以减少比较次数。

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

*Note: * You may assume k is always valid, 1 ≤ k ≤ n2.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.diguage.algorithm.leetcode;

/**
 * = 378. Kth Smallest Element in a Sorted Matrix
 *
 * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/[Kth Smallest Element in a Sorted Matrix - LeetCode]
 *
 * Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
 *
 * Note that it is the kth smallest element in the sorted order, not the kth distinct element.
 *
 * .Example:
 * [source]
 * ----
 * matrix = [
 *    [ 1,  5,  9],
 *    [10, 11, 13],
 *    [12, 13, 15]
 * ],
 * k = 8,
 *
 * return 13.
 * ----
 *
 * *Note:*
 *
 * You may assume k is always valid, 1 ≤ k ≤ n2.
 *
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-23 18:08
 */
public class _0378_KthSmallestElementInASortedMatrix {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Kth Smallest Element in a Sorted Matrix.
     *
     * Memory Usage: 56.2 MB, less than 5.41% of Java online submissions for Kth Smallest Element in a Sorted Matrix.
     *
     * Copy from: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/85173/Share-my-thoughts-and-Clean-Java-Code[Share my thoughts and Clean Java Code - LeetCode Discuss]
     */
    public int kthSmallest(int[][] matrix, int k) {
        int low = matrix[0][0];
        int length = matrix.length;
        int high = matrix[length - 1][length - 1];
        while (low < high) {
            int mid = low + (high - low) / 2;
            int count = 0;
            int j = length - 1;
            for (int i = 0; i < length; i++) {
                while (j >= 0 && mid < matrix[i][j]) {
                    j--;
                }
                count += (j + 1);
            }
            if (count < k) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }

    public static void main(String[] args) {
        _0378_KthSmallestElementInASortedMatrix solution = new _0378_KthSmallestElementInASortedMatrix();
        int[][] matrix = {
                {1, 5, 9},
                {10, 11, 13},
                {12, 13, 15}
        };
        int r1 = solution.kthSmallest(matrix, 8);
        System.out.println((r1 == 13) + " : " + r1);
    }
}

379. Design Phone Directory

1
Unresolved directive in 0379-design-phone-directory.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0379_DesignPhoneDirectory.java[]

380. Insert Delete GetRandom O(1)

Design a data structure that supports all following operations in average O(1) time.

  1. insert(val): Inserts an item val to the set if not already present.

  2. remove(val): Removes an item val from the set if present.

  3. getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.

Example:

// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();

// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);

// Returns false as 2 does not exist in the set.
randomSet.remove(2);

// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);

// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();

// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);

// 2 was already in the set, so return false.
randomSet.insert(2);

// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom();
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 380. Insert Delete GetRandom O(1)
 *
 * https://leetcode.com/problems/insert-delete-getrandom-o1/[Insert Delete GetRandom O(1) - LeetCode]
 *
 * Design a data structure that supports all following operations in average *O(1)* time.
 *
 * . `insert(val)`: Inserts an item val to the set if not already present.
 * . `remove(val)`: Removes an item val from the set if present.
 * . `getRandom`: Returns a random element from current set of elements. Each element must have the *same probability* of being returned.
 *
 * .Example:
 * [source]
 * ----
 * // Init an empty set.
 * RandomizedSet randomSet = new RandomizedSet();
 *
 * // Inserts 1 to the set. Returns true as 1 was inserted successfully.
 * randomSet.insert(1);
 *
 * // Returns false as 2 does not exist in the set.
 * randomSet.remove(2);
 *
 * // Inserts 2 to the set, returns true. Set now contains [1,2].
 * randomSet.insert(2);
 *
 * // getRandom should return either 1 or 2 randomly.
 * randomSet.getRandom();
 *
 * // Removes 1 from the set, returns true. Set now contains [2].
 * randomSet.remove(1);
 *
 * // 2 was already in the set, so return false.
 * randomSet.insert(2);
 *
 * // Since 2 is the only number in the set, getRandom always return 2.
 * randomSet.getRandom();
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-05 23:47
 */
public class _0380_InsertDeleteGetRandomO1 {
    public static void main(String[] args) {
        RandomizedSet solution = new RandomizedSet();
        solution.insert(3);
        solution.insert(3);
        solution.insert(1);
        solution.remove(3);
        int random = solution.getRandom();
        System.out.println(random);
    }

    /**
     * Runtime: 12 ms, faster than 47.51% of Java online submissions for Insert Delete GetRandom O(1).
     *
     * Memory Usage: 44 MB, less than 96.00% of Java online submissions for Insert Delete GetRandom O(1).
     *
     * Copy from: https://leetcode.com/problems/insert-delete-getrandom-o1/submissions/[Insert Delete GetRandom O(1) - LeetCode]
     */
    static
    class RandomizedSet {

        private List<Integer> nums;
        private Map<Integer, Integer> numToIndexMap;

        /** Initialize your data structure here. */
        public RandomizedSet() {
            nums = new ArrayList<>();
            numToIndexMap = new HashMap<>();
        }

        /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
        public boolean insert(int val) {
            if (numToIndexMap.containsKey(val)) {
                return false;
            }
            numToIndexMap.put(val, nums.size());
            nums.add(val);
            return true;
        }

        /** Removes a value from the set. Returns true if the set contained the specified element. */
        public boolean remove(int val) {
            if (!numToIndexMap.containsKey(val)) {
                return false;
            }
            Integer index = numToIndexMap.get(val);
            if (index < nums.size() - 1) {
                Integer lastNum = nums.get(nums.size() - 1);
                nums.set(index, lastNum);
                numToIndexMap.put(lastNum, index);
            }
            numToIndexMap.remove(val);
            nums.remove(nums.size() - 1);
            return true;
        }

        /** Get a random element from the set. */
        public int getRandom() {
            Random random = new Random();
            return nums.get(random.nextInt(nums.size()));
        }
    }
}



/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */

381. Insert Delete GetRandom O(1) - Duplicates allowed

Design a data structure that supports all following operations in average O(1) time. Note: Duplicate elements are allowed.

  1. insert(val): Inserts an item val to the collection.

  2. remove(val): Removes an item val from the collection if present.

  3. getRandom: Returns a random element from current collection of elements. The probability of each element being returned is linearly related to the number of same value the collection contains.

Example:

// Init an empty collection.
RandomizedCollection collection = new RandomizedCollection();

// Inserts 1 to the collection. Returns true as the collection did not contain 1.
collection.insert(1);

// Inserts another 1 to the collection. Returns false as the collection contained 1. Collection now contains [1,1].
collection.insert(1);

// Inserts 2 to the collection, returns true. Collection now contains [1,1,2].
collection.insert(2);

// getRandom should return 1 with the probability 2/3, and returns 2 with the probability 1/3.
collection.getRandom();

// Removes 1 from the collection, returns true. Collection now contains [1,2].
collection.remove(1);

// getRandom should return 1 and 2 both equally likely.
collection.getRandom();
1
Unresolved directive in 0381-insert-delete-getrandom-o1-duplicates-allowed.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0381_InsertDeleteGetRandomO1DuplicatesAllowed.java[]

382. Linked List Random Node

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Follow up:

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();
1
Unresolved directive in 0382-linked-list-random-node.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0382_LinkedListRandomNode.java[]

383. Ransom Note

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:

You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
1
Unresolved directive in 0383-ransom-note.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0383_RansomNote.java[]

384. Shuffle an Array

Shuffle a set of numbers without duplicates.

Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();

又学习了一个算法:Fisher-Yates Algorithm。

参考资料

Shuffle a set of numbers without duplicates.

Example:

// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
package com.diguage.algorithm.leetcode;

import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;

/**
 * = 384. Shuffle an Array
 *
 * https://leetcode.com/problems/shuffle-an-array/[Shuffle an Array - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 15:51
 */
public class _0384_ShuffleAnArray {

    /**
     * Runtime: 146 ms, faster than 8.33% of Java online submissions for Shuffle an Array.
     *
     * Memory Usage: 95.1 MB, less than 6.45% of Java online submissions for Shuffle an Array.
     *
     * Copy from: https://leetcode.com/problems/shuffle-an-array/solution/[Shuffle an Array - LeetCode]
     */
    class Solution {
        private int[] origin;

        public Solution(int[] nums) {
            this.origin = nums;
        }

        /**
         * Resets the array to its original configuration and return it.
         */
        public int[] reset() {
            return this.origin;
        }

        /**
         * Returns a random shuffling of the array.
         *
         * Fisher-Yates Algorithm
         */
        public int[] shuffle() {
            if (Objects.isNull(this.origin)) {
                return null;
            }
            int[] result = this.origin.clone();
            ThreadLocalRandom random = ThreadLocalRandom.current();
            int length = this.origin.length;
            for (int i = 0; i < length; i++) {
                int temp = result[i];
                int index = random.nextInt(i, length);
                result[i] = result[index];
                result[index] = temp;
            }
            return result;
        }
    }

    /**
     * Runtime: 90 ms, faster than 39.11% of Java online submissions for Shuffle an Array.
     *
     * Memory Usage: 50.7 MB, less than 100.00% of Java online submissions for Shuffle an Array.
     */
    class SolutionBruteForce {
        private int[] origin;

        public SolutionBruteForce(int[] nums) {
            this.origin = nums;
        }

        /**
         * Resets the array to its original configuration and return it.
         */
        public int[] reset() {
            return this.origin;
        }

        /**
         * Returns a random shuffling of the array.
         */
        public int[] shuffle() {
            if (Objects.isNull(this.origin)) {
                return null;
            }
            int[] result = new int[this.origin.length];
            ThreadLocalRandom random = ThreadLocalRandom.current();
            LinkedHashSet<Integer> index = new LinkedHashSet<>();
            while (index.size() < this.origin.length) {
                index.add(random.nextInt(this.origin.length));
            }
            int i = 0;
            for (Integer integer : index) {
                result[i++] = this.origin[integer];
            }
            return result;
        }
    }

    private void test() {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
        Solution solution = new Solution(nums);
        int[] reset = solution.reset();
        int[] shuffle = solution.shuffle();
    }

    public static void main(String[] args) {
        _0384_ShuffleAnArray solution = new _0384_ShuffleAnArray();
        solution.test();
    }
}

385. Mini Parser

Given a nested list of integers represented as a string, implement a parser to deserialize it.

Each element is either an integer, or a list — whose elements may also be integers or other lists.

Note: You may assume that the string is well-formed:

  • String is non-empty.

  • String does not contain white spaces.

  • String contains only digits 0-9, [, - ,, ].

Example 1:

Given s = "324",

You should return a NestedInteger object which contains a single integer 324.

Example 2:

Given s = "[123,[456,[789]]]",

Return a NestedInteger object containing a nested list with 2 elements:

1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789.
1
Unresolved directive in 0385-mini-parser.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0385_MiniParser.java[]

386. Lexicographical Numbers

Given an integer n, return 1 - n in lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.

1
Unresolved directive in 0386-lexicographical-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0386_LexicographicalNumbers.java[]

387. First Unique Character in a String

还是要善用 Map 来统计字符数量!

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 387. First Unique Character in a String
 *
 * https://leetcode.com/problems/first-unique-character-in-a-string/[First Unique Character in a String - LeetCode]
 *
 * Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
 *
 * .Examples:
 * [source]
 * ----
 * s = "leetcode"
 * return 0.
 *
 * s = "loveleetcode",
 * return 2.
 * ----
 *
 * *Note:* You may assume the string contain only lowercase letters.
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-11 10:48
 */
public class _0387_FirstUniqueCharacterInAString {
    /**
     * Runtime: 34 ms, faster than 54.19% of Java online submissions for First Unique Character in a String.
     *
     * Memory Usage: 37.4 MB, less than 100.00% of Java online submissions for First Unique Character in a String.
     *
     * Copy from: https://leetcode.com/problems/first-unique-character-in-a-string/solution/[First Unique Character in a String solution - LeetCode]
     */
    public int firstUniqChar(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return -1;
        }
        char[] chars = s.toCharArray();
        Map<Character, Integer> charToCountMap = new HashMap<>();
        for (char aChar : chars) {
            Integer count = charToCountMap.getOrDefault(aChar, 0);
            charToCountMap.put(aChar, ++count);
        }
        for (int i = 0; i < chars.length; i++) {
            if (charToCountMap.get(chars[i]) == 1) {
                return i;
            }
        }
        return -1;
    }
    /**
     * Runtime: 53 ms, faster than 10.48% of Java online submissions for First Unique Character in a String.
     *
     * Memory Usage: 38.4 MB, less than 96.43% of Java online submissions for First Unique Character in a String.
     */
    public int firstUniqCharArray(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return -1;
        }
        char[] chars = s.toCharArray();
        boolean[] unique = new boolean[chars.length];
        Arrays.fill(unique, true);
        for (int i = 0; i < chars.length; i++) {
            if (!unique[i]) {
                continue;
            }
            for (int j = i + 1; j < chars.length; j++) {
                if (!unique[j]) {
                    continue;
                }
                if (chars[i] == chars[j]) {
                    unique[i] = false;
                    unique[j] = false;
                }
            }
        }
        for (int i = 0; i < unique.length; i++) {
            if (unique[i]) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        _0387_FirstUniqueCharacterInAString solution = new _0387_FirstUniqueCharacterInAString();
        int r1 = solution.firstUniqChar("leetcode");
        System.out.println((r1 == 0) + " : " + r1);

        int r2 = solution.firstUniqChar("cc");
        System.out.println((r2 == -1) + " : " + r2);
    }
}

388. Longest Absolute File Path

Suppose we abstract our file system by a string in the following manner:

The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:

dir
    subdir1
    subdir2
        file.ext

The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.

The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents:

dir
    subdir1
        file1.ext
        subsubdir1
    subdir2
        subsubdir2
            file2.ext

The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.

We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes).

Given a string representing the file system in the above format, return the length of the longest absolute path to file in the abstracted file system. If there is no file in the system, return 0.

Note:

  • The name of a file contains at least a . and an extension.

  • The name of a directory or sub-directory will not contain a ..

Time complexity required: O(n) where n is the size of the input string.

Notice that a/aa/aaa/file1.txt is not the longest file path, if there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.

1
Unresolved directive in 0388-longest-absolute-file-path.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0388_LongestAbsoluteFilePath.java[]

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
1
Unresolved directive in 0389-find-the-difference.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0389_FindTheDifference.java[]

390. Elimination Game

There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

We keep repeating the steps again, alternating left to right and right to left, until a single number remains.

Find the last number that remains starting with a list of length n.

Example:

Input:
n = 9,
[.underline]1 2 [.underline]3 4 [.underline]5 6 [.underline]7 8 [.underline]9
2 [.underline]4 6 [.underline]8
[.underline]2 6
6

Output:
6
1
Unresolved directive in 0390-elimination-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0390_EliminationGame.java[]

391. Perfect Rectangle

Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.

Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).

rectangle perfect

Example 1:

rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [3,2,4,4],
  [1,3,2,4],
  [2,3,3,4]
]

Return true. All 5 rectangles together form an exact cover of a rectangular region.
rectangle separated

Example 2:

rectangles = [
  [1,1,2,3],
  [1,3,2,4],
  [3,1,4,2],
  [3,2,4,4]
]

Return false. Because there is a gap between the two rectangular regions.
rectangle hole

Example 3:

rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [3,2,4,4]
]

Return false. Because there is a gap in the top center.
rectangle intersect

Example 4:

rectangles = [
  [1,1,3,3],
  [3,1,4,2],
  [1,3,2,4],
  [2,2,4,4]
]

Return false. Because two of the rectangles overlap with each other.
1
Unresolved directive in 0391-perfect-rectangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0391_PerfectRectangle.java[]

392. Is Subsequence

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (⇐100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

s = "abc", t = "ahbgdc"

Return true.

Example 2:

s = "axc", t = "ahbgdc"

Return false.

Follow up:

If there are lots of incoming S, say S1, S2, …​ , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

Credits:

Special thanks to <a href="https://leetcode.com/pbrother/">@pbrother</a> for adding this problem and creating all test cases.

1
Unresolved directive in 0392-is-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0392_IsSubsequence.java[]

393. UTF-8 Validation

A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:

  1. For 1-byte character, the first bit is a 0, followed by its unicode code.

  2. For n-bytes character, the first n-bits are all one’s, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.

This is how the UTF-8 encoding would work:

   Char. number range  |        UTF-8 octet sequence
      (hexadecimal)    |              (binary)
   --------------------+---------------------------------------------
   0000 0000-0000 007F | 0xxxxxxx
   0000 0080-0000 07FF | 110xxxxx 10xxxxxx
   0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
   0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Given an array of integers representing the data, return whether it is a valid utf-8 encoding.

Note:

The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.

Example 1:

data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.

Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.

Example 2:

data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100.

Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
1
Unresolved directive in 0393-utf-8-validation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0393_UTF8Validation.java[]

394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

主要就是一个栈操作。不过,还需要注意一些细节。

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

Examples:

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.diguage.algorithm.leetcode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Objects;

/**
 * = 394. Decode String
 *
 * https://leetcode.com/problems/decode-string/[Decode String - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 22:08
 */
public class _0394_DecodeString {

    /**
     * Runtime: 1 ms, faster than 64.03% of Java online submissions for Decode String.
     * Memory Usage: 37.4 MB, less than 5.68% of Java online submissions for Decode String.
     */
    public String decodeString(String s) {
        if (Objects.isNull(s) || s.length() == 0) {
            return "";
        }
        Deque<Integer> nums = new LinkedList<>();
        Deque<String> strings = new LinkedList<>();
        int num = 0;
        StringBuilder result = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '[') {
                nums.addLast(num);
                strings.addLast(result.toString());
                num = 0;
                result = new StringBuilder();
            } else if (c == ']') {
                StringBuilder sb = new StringBuilder();
                Integer n = nums.removeLast();
                for (int i = 0; i < n; i++) {
                    sb.append(result);
                }
                result = new StringBuilder(strings.removeLast() + sb.toString());
            } else if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            } else if (Character.isLetter(c)) {
                result.append(c);
            }
        }
        return result.toString();
    }

    public static void main(String[] args) {
        _0394_DecodeString solution = new _0394_DecodeString();
        String r1 = solution.decodeString("3[a]2[bc]");
        System.out.println("aaabcbc".equals(r1) + " : " + r1);

        String r2 = solution.decodeString("3[a2[c]]");
        System.out.println("accaccacc".equals(r2) + " : " + r2);

        String r3 = solution.decodeString("2[abc]3[cd]ef");
        System.out.println("abcabccdcdcdef".equals(r3) + " : " + r3);
    }
}

395. Longest Substring with At Least K Repeating Characters

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:
Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.
Example 1:
Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

解题思路:递归拆分子串,分治。先统计出每个字符出现的频次,维护一对双指针,从首尾开始统计,从首尾往中间排除,如果出现次数小于k则不可能出现在最终子串中,排除并挪动指针,然后得到临时子串,依次从头遍历,一旦发现出现频次小于k的字符,以该字符为分割线,分别递归求其最大值返回。

参考资料

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:
s = "aaabb", k = 3

Output:
3

The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input:
s = "ababbc", k = 2

Output:
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 395. Longest Substring with At Least K Repeating Characters
 *
 * https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/[Longest Substring with At Least K Repeating Characters - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-27 16:28
 */
public class _0395_LongestSubstringWithAtLeastKRepeatingCharacters {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Longest Substring with At Least K Repeating Characters.
     *
     * Memory Usage: 38.7 MB, less than 10.00% of Java online submissions for Longest Substring with At Least K Repeating Characters.
     *
     * Copy from: https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/solution/javadi-gui-by-tzfun/[Java递归 - 至少有K个重复字符的最长子串 - 力扣(LeetCode)]
     */
    public int longestSubstring(String s, int k) {
        if (Objects.isNull(s) || s.length() == 0 || k > s.length()) {
            return 0;
        }
        if (k < 2) {
            return s.length();
        }

        return count(s.toCharArray(), k, 0, s.length() - 1);
    }

    private int count(char[] chars, int k, int start, int end) {
        if (end - start + 1 < k) {
            return 0;
        }
        int[] times = new int[26];
        for (int i = start; i <= end; i++) {
            ++times[chars[i] - 'a'];
        }
        while (end - start + 1 > k && times[chars[start] - 'a'] < k) {
            ++start;
        }
        while (end - start + 1 > k && times[chars[end] - 'a'] < k) {
            --end;
        }
        if (end - start + 1 < k) {
            return 0;
        }
        for (int i = start; i <= end; i++) {
            if (times[chars[i] - 'a'] < k) {
                return Math.max(count(chars, k, start, i - 1), count(chars, k, i + 1, end));
            }
        }
        return end - start + 1;
    }

    public static void main(String[] args) {
        _0395_LongestSubstringWithAtLeastKRepeatingCharacters solution = new _0395_LongestSubstringWithAtLeastKRepeatingCharacters();
        int r1 = solution.longestSubstring("aaabb", 3);
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.longestSubstring("ababbc", 2);
        System.out.println((r2 == 5) + " : " + r2);
    }
}

396. Rotate Function

Given an array of integers A and let n to be its length.

Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F on A as follow:

F(k) = 0 * Bk[0] + 1 * Bk[1] + …​ + (n-1) * Bk[n-1].

Calculate the maximum value of F(0), F(1), …​, F(n-1).

Note:

n is guaranteed to be less than 105.

Example:

A = [4, 3, 2, 6]

F(0) = (0  4) + (1  3) + (2  2) + (3  6) = 0 + 3 + 4 + 18 = 25
F(1) = (0  6) + (1  4) + (2  3) + (3  2) = 0 + 4 + 6 + 6 = 16
F(2) = (0  2) + (1  6) + (2  4) + (3  3) = 0 + 6 + 8 + 9 = 23
F(3) = (0  3) + (1  2) + (2  6) + (3  4) = 0 + 2 + 12 + 12 = 26

So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
1
Unresolved directive in 0396-rotate-function.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0396_RotateFunction.java[]

397. Integer Replacement

Given a positive integer n and you can do operations as follow:

  1. If n is even, replace n with n/2.

  2. If n is odd, you can replace n with either n + 1 or n - 1.

What is the minimum number of replacements needed for n to become 1?

Example 1:

Input:
8

Output:
3

Explanation:
8 -> 4 -> 2 -> 1

Example 2:

Input:
7

Output:
4

Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
1
Unresolved directive in 0397-integer-replacement.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0397_IntegerReplacement.java[]

398. Random Pick Index

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:

The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
1
Unresolved directive in 0398-random-pick-index.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0398_RandomPickIndex.java[]

399. Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:

Given ` a / b = 2.0, b / c = 3.0.`

queries are: ` a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .`

return ` [6.0, 0.5, -1.0, 1.0, -1.0 ].`

The input is: ` vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where `equations.size() == values.size(), and the values are positive. This represents the equations. Return ` vector<double>`.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].

The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

1
Unresolved directive in 0399-evaluate-division.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0399_EvaluateDivision.java[]

400. Nth Digit

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …​

Note:

n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:
3

Output:
3

Example 2:

Input:
11

Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
1
Unresolved directive in 0400-nth-digit.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0400_NthDigit.java[]

401. Binary Watch

A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.

Binary clock samui moon

For example, the above binary watch reads "3:25".

Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.

Example:

Input: n = 1
Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]

Note:

  • The order of output does not matter.

  • The hour must not contain a leading zero, for example "01:00" is not valid, it should be "1:00".

  • The minute must be consist of two digits and may contain a leading zero, for example "10:2" is not valid, it should be "10:02".

1
Unresolved directive in 0401-binary-watch.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0401_BinaryWatch.java[]

402. Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Note:

  • The length of num is less than 10002 and will be ≥ k.

  • The given num does not contain any leading zero.

Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.

Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.

Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
1
Unresolved directive in 0402-remove-k-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0402_RemoveKDigits.java[]

403. Frog Jump

A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river by landing on the last stone. Initially, the frog is on the first stone and assume the first jump must be 1 unit.

If the frog’s last jump was k units, then its next jump must be either k - 1, k, or k + 1 units. Note that the frog can only jump in the forward direction.

Note:

  • The number of stones is ≥ 2 and is < 1,100.

  • Each stone’s position will be a non-negative integer < 231.

  • The first stone’s position is always 0.

Example 1:

[0,1,3,5,6,8,12,17]

There are a total of 8 stones.
The first stone at the 0th unit, second stone at the 1st unit,
third stone at the 3rd unit, and so on...
The last stone at the 17th unit.

Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone,
4 units to the 7th stone, and 5 units to the 8th stone.

Example 2:

[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as
the gap between the 5th and 6th stone is too large.
1
Unresolved directive in 0403-frog-jump.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0403_FrogJump.java[]

404. Sum of Left Leaves

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

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
1
Unresolved directive in 0404-sum-of-left-leaves.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0404_SumOfLeftLeaves.java[]

405. Convert a Number to Hexadecimal

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.

  2. The hexadecimal string must not contain extra leading 0`s. If the number is zero, it is represented by a single zero character ’0'; otherwise, the first character in the hexadecimal string will not be the zero character.

  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.

  4. You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

Input:
26

Output:
"1a"

Example 2:

Input:
-1

Output:
"ffffffff"
1
Unresolved directive in 0405-convert-a-number-to-hexadecimal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0405_ConvertANumberToHexadecimal.java[]

406. Queue Reconstruction by Height

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:

The number of people is less than 1,100.

Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

这道题有点不明觉厉。

参考资料

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:

The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * = 406. Queue Reconstruction by Height
 *
 * https://leetcode.com/problems/queue-reconstruction-by-height/[Queue Reconstruction by Height - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 17:20
 */
public class _0406_QueueReconstructionByHeight {
    /**
     * Runtime: 8 ms, faster than 39.43% of Java online submissions for Queue Reconstruction by Height.
     * Memory Usage: 42.6 MB, less than 89.36% of Java online submissions for Queue Reconstruction by Height.
     */
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
        List<int[]> queue = new LinkedList<>();
        for (int[] person : people) {
            queue.add(person[1], person);
        }
        int length = people.length;
        return queue.toArray(new int[length][2]);
    }

    public static void main(String[] args) {
        _0406_QueueReconstructionByHeight solution = new _0406_QueueReconstructionByHeight();
        int[][] p1 = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};
        int[][] r1 = solution.reconstructQueue(p1);
        System.out.println(Arrays.deepToString(p1));
    }
}

407. Trapping Rain Water II

Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevation map, compute the volume of water it is able to trap after raining.

Note:

Both m and n are less than 110. The height of each unit cell is greater than 0 and is less than 20,000.

Example:

Given the following 3x6 height map:
[
  [1,4,3,1,3,2],
  [3,2,1,3,2,4],
  [2,3,3,2,3,1]
]

Return 4.
rainwater empty

The above image represents the elevation map [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.

rainwater fill

After the rain, water is trapped between the blocks. The total volume of water trapped is 4.

1
Unresolved directive in 0407-trapping-rain-water-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0407_TrappingRainWaterII.java[]

408. Valid Word Abbreviation

1
Unresolved directive in 0408-valid-word-abbreviation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0408_ValidWordAbbreviation.java[]

409. Longest Palindrome

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: *

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
1
Unresolved directive in 0409-longest-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0409_LongestPalindrome.java[]

410. Split Array Largest Sum

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.

Note:

If n is the length of array, assume the following constraints are satisfied:

  • 1 ≤ n ≤ 1000

  • 1 ≤ m ≤ min(50, n)

*Examples: *

Input:
nums = [7,2,5,10,8]
m = 2

Output:
18

Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
1
Unresolved directive in 0410-split-array-largest-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0410_SplitArrayLargestSum.java[]

411. Minimum Unique Word Abbreviation

1
Unresolved directive in 0411-minimum-unique-word-abbreviation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0411_MinimumUniqueWordAbbreviation.java[]

412. Fizz Buzz

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:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * = 412. Fizz Buzz
 *
 * https://leetcode.com/problems/fizz-buzz/[Fizz Buzz - LeetCode]
 *
 * 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”.
 *
 * .Examples:
 * [source]
 * ----
 * n = 15,
 *
 * Return:
 * [
 *     "1",
 *     "2",
 *     "Fizz",
 *     "4",
 *     "Buzz",
 *     "Fizz",
 *     "7",
 *     "8",
 *     "Fizz",
 *     "Buzz",
 *     "11",
 *     "Fizz",
 *     "13",
 *     "14",
 *     "FizzBuzz"
 * ]
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-26 23:17
 */
public class _0412_FizzBuzz {

    /**
     * Runtime: 2 ms, faster than 29.17% of Java online submissions for Fizz Buzz.
     *
     * Memory Usage: 45.5 MB, less than 5.40% of Java online submissions for Fizz Buzz.
     */
    public List<String> fizzBuzz(int n) {
        List<String> result = new ArrayList<>(n);
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                result.add("FizzBuzz");
            } else if (i % 5 == 0) {
                result.add("Buzz");
            } else if (i % 3 == 0) {
                result.add("Fizz");
            } else {
                result.add(String.valueOf(i));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0412_FizzBuzz solution = new _0412_FizzBuzz();
        System.out.println(solution.fizzBuzz(15));
    }
}

413. Arithmetic Slices

A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequence:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic. [subs="verbatim,quotes,macros"]

1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 ⇐ P < Q < N.

A slice (P, Q) of array A is called arithmetic if the sequence:<br/> A[P], A[p + 1], …​, A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.

The function should return the number of arithmetic slices in the array A. <br/>

Example:

A = [1, 2, 3, 4]

return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
1
Unresolved directive in 0413-arithmetic-slices.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0413_ArithmeticSlices.java[]

414. Third Maximum Number

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

Example 2:

Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
1
Unresolved directive in 0414-third-maximum-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0414_ThirdMaximumNumber.java[]

415. Add Strings

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.

  2. Both num1 and num2 contains only digits 0-9.

  3. Both num1 and num2 does not contain any leading zero.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

1
Unresolved directive in 0415-add-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0415_AddStrings.java[]

416. Partition Equal Subset Sum

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:

  1. Each of the array element will not exceed 100.

  2. The array size will not exceed 200.

Example 1:
Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.

这道题使用回溯法更容易理解,也更高效。

0416 1

思考题

  1. 将计算过程在纸上手动推演一遍;

  2. 研究一下背包问题。

参考资料

Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.

Note:

  1. Each of the array element will not exceed 100.

  2. The array size will not exceed 200.

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be partitioned as [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: The array cannot be partitioned into equal sum subsets.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.diguage.algorithm.leetcode;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 19:30
 */
public class _0416_PartitionEqualSubsetSum {
    /**
     * Runtime: 10 ms, faster than 72.90% of Java online submissions for Partition Equal Subset Sum.
     * Memory Usage: 37.8 MB, less than 50.79% of Java online submissions for Partition Equal Subset Sum.
     *
     * https://leetcode-cn.com/problems/partition-equal-subset-sum/solution/0-1-bei-bao-wen-ti-xiang-jie-zhen-dui-ben-ti-de-yo/[动态规划(0-1 背包问题) - 分割等和子集 - 力扣(LeetCode)]
     */
    public boolean canPartitionDp(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return false;
        }
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if ((sum & 1) == 1) {
            return false;
        }
        int target = sum / 2;
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;
        if (nums[0] <= target) {
            dp[nums[0]] = true;
        }

        for (int i = 1; i < nums.length; i++) {
            for (int j = target; nums[i] <= j; j--) {
                if (dp[target]) {
                    return true;
                }
                dp[j] = dp[j] || dp[j - nums[i]];
            }
        }
        return dp[target];
    }

    /**
     * Runtime: 2 ms, faster than 91.78% of Java online submissions for Partition Equal Subset Sum.
     * Memory Usage: 39.6 MB, less than 6.35% of Java online submissions for Partition Equal Subset Sum.
     *
     * Copy from: https://leetcode-cn.com/problems/partition-equal-subset-sum/solution/java-hui-su-fa-jie-fa-2ms-by-wang_dong/[java 回溯法解法 2ms - 分割等和子集 - 力扣(LeetCode)]
     */
    public boolean canPartition(int[] nums) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return true;
        }
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if ((sum & 1) == 1) {
            return false;
        }
        Arrays.sort(nums);
        reverse(nums);
        return canPartition(nums, sum / 2, 0);
    }

    private boolean canPartition(int[] nums, int target, int index) {
        if (index >= nums.length || nums[index] > target) {
            return false;
        }
        if (nums[index] == target) {
            return true;
        }
        return canPartition(nums, target - nums[index], index + 1)
                || canPartition(nums, target, index + 1);
    }

    private void reverse(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        _0416_PartitionEqualSubsetSum solution = new _0416_PartitionEqualSubsetSum();
        int[] n1 = {1, 5, 11, 5};
        System.out.println(solution.canPartition(n1));

        int[] n2 = {1, 2, 3, 5};
        System.out.println(!solution.canPartition(n2));
    }
}

417. Pacific Atlantic Water Flow

Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:

  1. The order of returned grid coordinates does not matter.

  2. Both m and n are less than 150.

Example:

Given the following 5x5 matrix:

  Pacific ~   ~   ~   ~   ~
       ~  1   2   2   3  (5) 
       ~  3   2   3  (4) (4) 
       ~  2   4  (5)  3   1  
       ~ (6) (7)  1   4   5  
       ~ (5)  1   1   2   4  
                       Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
1
Unresolved directive in 0417-pacific-atlantic-water-flow.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0417_PacificAtlanticWaterFlow.java[]

418. Sentence Screen Fitting

1
Unresolved directive in 0418-sentence-screen-fitting.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0418_SentenceScreenFitting.java[]

419. Battleships in a Board

Given an 2D board, count how many battleships are in it. The battleships are represented with ’X'`s, empty slots are represented with ’.'`s. You may assume the following rules:

  1. You receive a valid board, made of only battleships or empty slots.

  2. Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.

  3. At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.

Example:

X..X
...X
...X

In the above board there are 2 battleships.

Invalid Example:

...X
XXXX
...X

This is an invalid board that you will not receive - as battleships will always have a cell separating between them.

Follow up:

Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?

1
Unresolved directive in 0419-battleships-in-a-board.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0419_BattleshipsInABoard.java[]

420. Strong Password Checker

A password is considered strong if below conditions are all met:

  1. It has at least 6 characters and at most 20 characters.

  2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.

  3. It must NOT contain three repeating characters in a row ("…​aaa…​" is weak, but "…​aa…​a…​" is strong, assuming other conditions are met).

Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.

Insertion, deletion or replace of any one character are all considered as one change.

1
Unresolved directive in 0420-strong-password-checker.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0420_StrongPasswordChecker.java[]

421. Maximum XOR of Two Numbers in an Array

Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.

Could you do this in O(n) runtime?

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.
1
Unresolved directive in 0421-maximum-xor-of-two-numbers-in-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0421_MaximumXOROfTwoNumbersInAnArray.java[]

422. Valid Word Square

1
Unresolved directive in 0422-valid-word-square.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0422_ValidWordSquare.java[]

423. Reconstruct Original Digits from English

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.

Note:

  1. Input contains only lowercase English letters.

  2. Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.

  3. Input length is less than 50,000.

Example 1:

Input: "owoztneoer"

Output: "012"

Example 2:

Input: "fviefuro"

Output: "45"
1
Unresolved directive in 0423-reconstruct-original-digits-from-english.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0423_ReconstructOriginalDigitsFromEnglish.java[]

424. Longest Repeating Character Replacement

Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string.

In one operation, you can choose any character of the string and change it to any other uppercase English character.

Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.

Note:

Both the string’s length and k will not exceed 104.

Example 1:

Input:
s = "ABAB", k = 2

Output:
4

Explanation:
Replace the two 'A's with two 'B's or vice versa.

Example 2:

Input:
s = "AABABBA", k = 1

Output:
4

Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
1
Unresolved directive in 0424-longest-repeating-character-replacement.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0424_LongestRepeatingCharacterReplacement.java[]

425. Word Squares

1
Unresolved directive in 0425-word-squares.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0425_WordSquares.java[]

426. Convert Binary Search Tree to Sorted Doubly Linked List

1
Unresolved directive in 0426-convert-binary-search-tree-to-sorted-doubly-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0426_ConvertBinarySearchTreeToSortedDoublyLinkedList.java[]

427. Construct Quad Tree

We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same.

Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.

Your task is to use a quad tree to represent a given grid. The following example may help you understand the problem better:

Given the 8 x 8 grid below, we want to construct the corresponding quad tree:

962 grid

It can be divided according to the definition above:

962 grid divided

The corresponding quad tree should be as following, where each node is represented as a (isLeaf, val) pair.

For the non-leaf nodes, val can be arbitrary, so it is represented as *.

962 quad tree

Note:

  1. N is less than 1000 and guaranteened to be a power of 2.

  2. If you want to know more about the quad tree, you can refer to its <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.

1
Unresolved directive in 0427-construct-quad-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0427_ConstructQuadTree.java[]

428. Serialize and Deserialize N-ary Tree

1
Unresolved directive in 0428-serialize-and-deserialize-n-ary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0428_SerializeAndDeserializeNAryTree.java[]

429. N-ary Tree Level Order Traversal

Given an n-ary tree, return the level order traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Example 1:

narytreeexample
Input: root = [1,null,3,2,4,null,5,6]
Output: [[1],[3,2,4],[5,6]]

Example 2:

sample 4 964
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]

Constraints:

  • The height of the n-ary tree is less than or equal to 1000

  • The total number of nodes is between [0, 10^4]

1
Unresolved directive in 0429-n-ary-tree-level-order-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0429_NAryTreeLevelOrderTraversal.java[]

430. Flatten a Multilevel Doubly Linked List

You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

Example 1:

Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation:

The multilevel linked list in the input is as follows:

:https://assets.leetcode.com/uploads/2018/10/12/multilevellinkedlist.png" alt="multilevellinkedlist">

After flattening the multilevel linked list it becomes:

:https://assets.leetcode.com/uploads/2018/10/12/multilevellinkedlistflattened.png" alt="multilevellinkedlistflattened">

Example 2:

Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation:

The input multilevel linked list is as follows:

  1---2---NULL
  |
  3---NULL

Example 3:

Input: head = []
Output: []

How multilevel linked list is represented in test case:

We use the multilevel linked list from Example 1 above:

 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL

The serialization of each level is as follows:

[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]

To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

[1,2,3,4,5,6,null]
[null,null,7,8,9,10,null]
[null,11,12,null]

Merging the serialization of each level and removing trailing nulls we obtain:

[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]

Constraints:

  • Number of Nodes will not exceed 1000.

  • 1 ⇐ Node.val ⇐ 10^5

1
Unresolved directive in 0430-flatten-a-multilevel-doubly-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0430_FlattenAMultilevelDoublyLinkedList.java[]

431. Encode N-ary Tree to Binary Tree

1
Unresolved directive in 0431-encode-n-ary-tree-to-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0431_EncodeNAryTreeToBinaryTree.java[]

432. All O`one Data Structure

Implement a data structure supporting the following operations:

  1. Inc(Key) - Inserts a new key <Key> with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string.

  2. Dec(Key) - If Key’s value is 1, remove it from the data structure. Otherwise decrements an existing key by 1. If the key does not exist, this function does nothing. Key is guaranteed to be a non-empty string.

  3. GetMaxKey() - Returns one of the keys with maximal value. If no element exists, return an empty string "".

  4. GetMinKey() - Returns one of the keys with minimal value. If no element exists, return an empty string "".

Challenge: Perform all these in O(1) time complexity.

1
Unresolved directive in 0432-all-oone-data-structure.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0432_AllOOneDataStructure.java[]

433. Minimum Genetic Mutation

A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".

Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.

For example, "AACCGGTT""AACCGGTA" is 1 mutation.

Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.

Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.

Note:

  1. Starting point is assumed to be valid, so it might not be included in the bank.

  2. If multiple mutations are needed, all mutations during in the sequence must be valid.

  3. You may assume start and end string is not the same.

Example 1:

start: "AACCGGTT"
end:   "AACCGGTA"
bank: ["AACCGGTA"]

return: 1

Example 2:

start: "AACCGGTT"
end:   "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]

return: 2

Example 3:

start: "AAAAACCC"
end:   "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]

return: 3
1
Unresolved directive in 0433-minimum-genetic-mutation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0433_MinimumGeneticMutation.java[]

434. Number of Segments in a String

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"
Output: 5
1
Unresolved directive in 0434-number-of-segments-in-a-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0434_NumberOfSegmentsInAString.java[]

435. Non-overlapping Intervals

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:

Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.

Example 2:

Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.

Example 3:

Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

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.

1
Unresolved directive in 0435-non-overlapping-intervals.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0435_NonOverlappingIntervals.java[]

436. Find Right Interval

Given a set of intervals, for each of the interval i, check if there exists an interval j whose start point is bigger than or equal to the end point of the interval i, which can be called that j is on the "right" of i.

For any interval i, you need to store the minimum interval j’s index, which means that the interval j has the minimum start point to build the "right" relationship for interval i. If the interval j doesn’t exist, store -1 for the interval i. Finally, you need output the stored value of each interval as an array.

Note:

  1. You may assume the interval’s end point is always bigger than its start point.

  2. You may assume none of these intervals have the same start point.

Example 1:

Input: [ [1,2] ]

Output: [-1]

Explanation: There is only one interval in the collection, so it outputs -1.

Example 2:

Input: [ [3,4], [2,3], [1,2] ]

Output: [-1, 0, 1]

Explanation: There is no satisfied "right" interval for [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point;
For [1,2], the interval [2,3] has minimum-"right" start point.

Example 3:

Input: [ [1,4], [2,3], [3,4] ]

Output: [-1, 2, -1]

Explanation: There is no satisfied "right" interval for [1,4] and [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point.

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1
Unresolved directive in 0436-find-right-interval.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0436_FindRightInterval.java[]

437. Path Sum III

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

思考题:感觉目前的解法还是有些繁琐。效仿 java解法 时间100% 空间93% - 路径总和 III - 力扣(LeetCode),设计一个更加高效的实现。

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Arrays;
import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;

/**
 * = 437. Path Sum III
 *
 * https://leetcode.com/problems/path-sum-iii/[Path Sum III - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 23:06
 */
public class _0437_PathSumIII {
    /**
     * Runtime: 23 ms, faster than 10.40% of Java online submissions for Path Sum III.
     * Memory Usage: 39.1 MB, less than 90.91% of Java online submissions for Path Sum III.
     *
     * Copy from: https://leetcode-cn.com/problems/path-sum-iii/solution/leetcode-437-path-sum-iii-by-li-xin-lei/[LeetCode 437 Path Sum III - 路径总和 III - 力扣(LeetCode)]
     */
    public int pathSum(TreeNode root, int sum) {
        if (Objects.isNull(root)) {
            return 0;
        }
        return pathSum(root.left, sum) + pathSum(root.right, sum) + childPathSum(root, sum);
    }

    private int childPathSum(TreeNode root, int sum) {
        if (Objects.isNull(root)) {
            return 0;
        }
        int result = 0;
        if (root.val == sum) {
            result++;
        }
        result += childPathSum(root.left, sum - root.val);
        result += childPathSum(root.right, sum - root.val);
        return result;
    }

    public static void main(String[] args) {
        _0437_PathSumIII solution = new _0437_PathSumIII();
        int r1 = solution.pathSum(buildTree(Arrays.asList(10, 5, -3, 3, 2, null, 11, 3, -2, null, 1)), 8);
        System.out.println((r1 == 3) + " : " + r1);
    }
}

438. Find All Anagrams in a String

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:
Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

解题分析

使用滑动窗口来"圈定"字符串!

思考题

尝试使用数组来代替 Map

参考资料

Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.

Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.

The order of output does not matter.

Example 1:

Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 438. Find All Anagrams in a String
 *
 * https://leetcode.com/problems/find-all-anagrams-in-a-string/[Find All Anagrams in a String - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 12:24
 */
public class _0438_FindAllAnagramsInAString {
    /**
     * Runtime: 18 ms, faster than 51.95% of Java online submissions for Find All Anagrams in a String.
     * Memory Usage: 42.6 MB, less than 6.00% of Java online submissions for Find All Anagrams in a String.
     *
     * Copy from: https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/solution/hua-dong-chuang-kou-tong-yong-si-xiang-jie-jue-zi-/[滑动窗口通用思想解决子串问题 - 找到字符串中所有字母异位词 - 力扣(LeetCode)]
     */
    public List<Integer> findAnagrams(String s, String p) {
        if (Objects.isNull(s) || s.length() == 0
                || Objects.isNull(p) || p.length() == 0
                || s.length() < p.length()) {
            return Collections.emptyList();
        }

        Map<Character, Integer> needs = new HashMap<>(p.length());
        for (char c : p.toCharArray()) {
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        Map<Character, Integer> windows = new HashMap<>(p.length());
        int match = 0;
        List<Integer> result = new ArrayList<>();
        while (right < s.length()) {
            char rChar = s.charAt(right);
            if (needs.containsKey(rChar)) {
                int rCount = windows.getOrDefault(rChar, 0) + 1;
                windows.put(rChar, rCount);
                if (rCount == needs.get(rChar)) {
                    match++;
                }
            }
            right++;

            while (match == needs.size()) {
                if (right - left == p.length()) {
                    result.add(left);
                }
                char lChar = s.charAt(left);
                if (needs.containsKey(lChar)) {
                    Integer lCount = windows.get(lChar) - 1;
                    windows.put(lChar, lCount);
                    if (lCount < needs.get(lChar)) {
                        match--;
                    }
                }
                left++;
            }
        }
        return result;
    }

    /**
     * Time Limit Exceeded
     */
    public List<Integer> findAnagramsSort(String s, String p) {
        if (Objects.isNull(s) || s.length() == 0
                || Objects.isNull(p) || p.length() == 0
                || s.length() < p.length()) {
            return Collections.emptyList();
        }
        char[] chars = p.toCharArray();
        Arrays.sort(chars);
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i <= s.length() - p.length(); i++) {
            char[] subchars = s.substring(i, i + p.length()).toCharArray();
            Arrays.sort(subchars);
            if (Arrays.equals(chars, subchars)) {
                result.add(i);
            }
        }
        return result;
    }

    /**
     * Time Limit Exceeded
     */
    public List<Integer> findAnagramsPermutations(String s, String p) {
        if (Objects.isNull(s) || s.length() == 0
                || Objects.isNull(p) || p.length() == 0
                || s.length() < p.length()) {
            return Collections.emptyList();
        }
        ArrayList<Character> chars = new ArrayList<>();
        for (char c : p.toCharArray()) {
            chars.add(c);
        }
        HashSet<String> anagrams = new HashSet<>();
        buildAnagrams(chars, anagrams, 0);
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i <= s.length() - p.length(); i++) {
            String substring = s.substring(i, i + p.length());
            if (anagrams.contains(substring)) {
                result.add(i);
            }
        }
        return result;
    }

    private void buildAnagrams(List<Character> chars, Set<String> result, int index) {
        if (index == chars.size()) {
            StringBuilder builder = new StringBuilder();
            for (Character aChar : chars) {
                builder.append(aChar);
            }
            result.add(builder.toString());
            return;
        }
        for (int i = index; i < chars.size(); i++) {
            Collections.swap(chars, i, index);
            buildAnagrams(chars, result, index + 1);
            Collections.swap(chars, i, index);
        }
    }


    public static void main(String[] args) {
        _0438_FindAllAnagramsInAString solution = new _0438_FindAllAnagramsInAString();

        List<Integer> r1 = solution.findAnagrams("cbaebabacd", "abc");
        System.out.println(r1);

        List<Integer> r2 = solution.findAnagrams("abab", "ab");
        System.out.println(r2);
    }
}

439. Ternary Expression Parser

1
Unresolved directive in 0439-ternary-expression-parser.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0439_TernaryExpressionParser.java[]

440. K-th Smallest in Lexicographical Order

Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.

Note: 1 ≤ k ≤ n ≤ 109.

Example:

Input:
n: 13   k: 2

Output:
10

Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
1
Unresolved directive in 0440-k-th-smallest-in-lexicographical-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0440_KThSmallestInLexicographicalOrder.java[]

441. Arranging Coins

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Example 2:

n = 8

The coins can form the following rows:
¤
¤ ¤
¤ ¤ ¤
¤ ¤

Because the 4th row is incomplete, we return 3.
1
Unresolved directive in 0441-arranging-coins.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0441_ArrangingCoins.java[]

442. Find All Duplicates in an Array

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:<br/>

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]
1
Unresolved directive in 0442-find-all-duplicates-in-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0442_FindAllDuplicatesInAnArray.java[]

443. String Compression

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

Follow up:

Could you solve it using only O(1) extra space?

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

Example 2:

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]

Explanation:
Nothing is replaced.

Example 3:

Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.

Note:

  1. All characters have an ASCII value in [35, 126].

  2. 1 ⇐ len(chars) ⇐ 1000.

1
Unresolved directive in 0443-string-compression.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0443_StringCompression.java[]

444. Sequence Reconstruction

1
Unresolved directive in 0444-sequence-reconstruction.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0444_SequenceReconstruction.java[]

445. Add Two Numbers II

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:

What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
1
Unresolved directive in 0445-add-two-numbers-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0445_AddTwoNumbersII.java[]

446. Arithmetic Slices II - Subsequence

A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

For example, these are arithmetic sequences:

1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic.

1, 1, 2, 5, 7

A zero-indexed array A consisting of N numbers is given. A subsequence slice of that array is any sequence of integers (P0, P1, …​, Pk) such that 0 ≤ P0 < P1 < …​ < Pk < N.

A subsequence slice (P0, P1, …​, Pk) of array A is called arithmetic if the sequence A[P0], A[P1], …​, A[Pk-1], A[Pk] is arithmetic. In particular, this means that k ≥ 2.

The function should return the number of arithmetic subsequence slices in the array A.

The input contains N integers. Every integer is in the range of -231 and 231-1 and 0 ≤ N ≤ 1000. The output is guaranteed to be less than 231-1.

Example:

Input: [2, 4, 6, 8, 10]

Output: 7

Explanation:
All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
1
Unresolved directive in 0446-arithmetic-slices-ii-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0446_ArithmeticSlicesIISubsequence.java[]

447. Number of Boomerangs

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).

Example:

Input:
[[0,0],[1,0],[2,0]]

Output:
2

Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
1
Unresolved directive in 0447-number-of-boomerangs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0447_NumberOfBoomerangs.java[]

448. Find All Numbers Disappeared in an Array

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:
Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]

解题分析

原地修改的思路有点绕。再推敲推敲。

0448 1
0448 2
0448 3

参考资料

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[5,6]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.diguage.algorithm.leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * = 448. Find All Numbers Disappeared in an Array
 *
 * https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/[Find All Numbers Disappeared in an Array - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 19:06
 */
public class _0448_FindAllNumbersDisappearedInAnArray {
    /**
     * Runtime: 5 ms, faster than 91.55% of Java online submissions for Find All Numbers Disappeared in an Array.
     * Memory Usage: 48.5 MB, less than 33.96% of Java online submissions for Find All Numbers Disappeared in an Array.
     */
    public List<Integer> findDisappearedNumbers(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int newIndex = Math.abs(nums[i]) - 1;
            if (nums[newIndex] > 0) {
                nums[newIndex] *= -1;
            }
        }
        List<Integer> result = new ArrayList<>();
        for (int i = 1; i <= nums.length; i++) {
            if (nums[i - 1] > 0) {
                result.add(i);
            }
        }
        return result;
    }

    /**
     * Runtime: 21 ms, faster than 26.28% of Java online submissions for Find All Numbers Disappeared in an Array.
     * Memory Usage: 53.1 MB, less than 15.09% of Java online submissions for Find All Numbers Disappeared in an Array.
     */
    public List<Integer> findDisappearedNumbersMap(int[] nums) {
        Set<Integer> result = new HashSet<>(nums.length);
        for (int i = 1; i <= nums.length; i++) {
            result.add(i);
        }
        for (int num : nums) {
            result.remove(num);
        }
        return new ArrayList<>(result);
    }

    public static void main(String[] args) {
        _0448_FindAllNumbersDisappearedInAnArray solution = new _0448_FindAllNumbersDisappearedInAnArray();
        int[] n1 = {4, 3, 2, 7, 8, 2, 3, 1};
        System.out.println(solution.findDisappearedNumbers(n1));
    }
}

449. Serialize and Deserialize BST

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

1
Unresolved directive in 0449-serialize-and-deserialize-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0449_SerializeAndDeserializeBST.java[]

450. Delete Node in a BST

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.

Note: Time complexity should be O(height of tree).

Example:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

Given key to delete is 3. So we find the node with value 3 and delete it.

One valid answer is [5,4,6,2,null,null,7], shown in the following BST.

    5
   / \
  4   6
 /     \
2       7

Another valid answer is [5,2,6,null,4,null,7].

    5
   / \
  2   6
   \   \
    4   7
1
Unresolved directive in 0450-delete-node-in-a-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0450_DeleteNodeInABST.java[]

451. Sort Characters By Frequency

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
1
Unresolved directive in 0451-sort-characters-by-frequency.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0451_SortCharactersByFrequency.java[]

452. Minimum Number of Arrows to Burst Balloons

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Example:

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
1
Unresolved directive in 0452-minimum-number-of-arrows-to-burst-balloons.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0452_MinimumNumberOfArrowsToBurstBalloons.java[]

453. Minimum Moves to Equal Array Elements

Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.

Example:

Input:
[1,2,3]

Output:
3

Explanation:
Only three moves are needed (remember each move increments two elements):

[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]
1
Unresolved directive in 0453-minimum-moves-to-equal-array-elements.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0453_MinimumMovesToEqualArrayElements.java[]

454. 4Sum II

原想是三层循环,就是 O(N3) 的复杂度。降低为两层循环,把时间复杂度也减低一级。

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

Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * = 454. 4Sum II
 *
 * https://leetcode.com/problems/4sum-ii/[4Sum II - LeetCode]
 *
 * 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 -2^28^ to 2^28^ - 1 and the result is guaranteed to be at most 2^31^ - 1.
 *
 * .Example:
 * [source]
 * ----
 * Input:
 * A = [ 1, 2]
 * B = [-2,-1]
 * C = [-1, 2]
 * D = [ 0, 2]
 *
 * Output:
 * 2
 *
 * Explanation:
 * The two tuples are:
 * 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
 * 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
 * ----
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-11 13:02
 */
public class _0454_4SumII {
    /**
     * Runtime: 94 ms, faster than 38.81% of Java online submissions for 4Sum II.
     *
     * Memory Usage: 58.6 MB, less than 64.00% of Java online submissions for 4Sum II.
     *
     * https://leetcode.com/problems/4sum-ii/discuss/93920/Clean-java-solution-O(n2)[Clean java solution O(n^2) - LeetCode Discuss]
     */
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        Map<Integer, Integer> numToCountMap = new HashMap<>();
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B.length; j++) {
                int value = A[i] + B[j];
                Integer count = numToCountMap.getOrDefault(value, 0);
                numToCountMap.put(value, ++count);
            }
        }
        int result = 0;
        for (int i = 0; i < C.length; i++) {
            for (int j = 0; j < D.length; j++) {
                result += numToCountMap.getOrDefault(0 - C[i] - D[j], 0);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _0454_4SumII solution = new _0454_4SumII();
        int r1 = solution.fourSumCount(new int[]{1, 2}, new int[]{-2, -1}, new int[]{-1, 2}, new int[]{0, 2});
        System.out.println((r1 == 2) + " : " + r1);
    }
}

455. Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:

You may assume the greed factor is always positive.

You cannot assign more than one cookie to one child.

Example 1:

Input: [1,2,3], [1,1]

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.

Example 2:

Input: [1,2], [1,2,3]

Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.
1
Unresolved directive in 0455-assign-cookies.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0455_AssignCookies.java[]

456. 132 Pattern

Given a sequence of n integers a1, a2, …​, an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

Note: n will be less than 15,000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
1
Unresolved directive in 0456-132-pattern.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0456_132Pattern.java[]

457. Circular Array Loop

You are given a circular array nums of positive and negative integers. If a number k at an index is positive, then move forward k steps. Conversely, if it’s negative (-k), move backward k steps. Since the array is circular, you may assume that the last element’s next element is the first element, and the first element’s previous element is the last element.

Determine if there is a loop (or a cycle) in nums. A cycle must start and end at the same index and the cycle’s length > 1. Furthermore, movements in a cycle must all follow a single direction. In other words, a cycle must not consist of both forward and backward movements.

Example 1:

Input: [2,-1,1,2,2]
Output: true
Explanation: There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle's length is 3.

Example 2:

Input: [-1,2]
Output: false
Explanation: The movement from index 1 -> 1 -> 1 ... is not a cycle, because the cycle's length is 1. By definition the cycle's length must be greater than 1.

Example 3:

Input: [-2,1,-1,-2,-2]
Output: false
Explanation: The movement from index 1 -> 2 -> 1 -> ... is not a cycle, because movement from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward movement. All movements in a cycle must follow a single direction.

Note:

  1. -1000 ≤ nums[i] ≤ 1000

  2. nums[i] ≠ 0

  3. 1 ≤ nums.length ≤ 5000

Follow up:

Could you solve it in O(n) time complexity and O(1) extra space complexity?

1
Unresolved directive in 0457-circular-array-loop.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0457_CircularArrayLoop.java[]

458. Poor Pigs

There are 1000 buckets, one and only one of them is poisonous, while the rest are filled with water. They all look identical. If a pig drinks the poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket is poisonous within one hour?

Answer this question, and write an algorithm for the general case.

*General case: *

If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the poisonous bucket within p minutes? There is exactly one bucket with poison.

Note:

  1. A pig can be allowed to drink simultaneously on as many buckets as one would like, and the feeding takes no time.

  2. After a pig has instantly finished drinking buckets, there has to be a cool down time of _m _minutes. During this time, only observation is allowed and no feedings at all.

  3. Any given bucket can be sampled an infinite number of times (by an unlimited number of pigs).

1
Unresolved directive in 0458-poor-pigs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0458_PoorPigs.java[]

459. Repeated Substring Pattern

Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.

Example 1:

Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.

Example 2:

Input: "aba"
Output: False

Example 3:

Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
1
Unresolved directive in 0459-repeated-substring-pattern.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0459_RepeatedSubstringPattern.java[]

460. LFU Cache

Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.

Note that the number of times an item is used is the number of calls to the get and put functions for that item since it was inserted. This number is set to zero when the item is removed.

Follow up:

Could you do both operations in O(1) time complexity?

Example:

LFUCache cache = new LFUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.get(3);       // returns 3.
cache.put(4, 4);    // evicts key 1.
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4
1
Unresolved directive in 0460-lfu-cache.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0460_LFUCache.java[]

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:

0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       &uarr;   &uarr;

The above arrows point to positions where the corresponding bits are different.
1
Unresolved directive in 0461-hamming-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0461_HammingDistance.java[]

462. Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array’s length is at most 10,000.

Example:

Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
1
Unresolved directive in 0462-minimum-moves-to-equal-array-elements-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0462_MinimumMovesToEqualArrayElementsII.java[]

463. Island Perimeter

You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.

Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn’t have "lakes" (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Example:

Input:
[[0,1,0,0],
 [1,1,1,0],
 [0,1,0,0],
 [1,1,0,0]]

Output: 16

Explanation: The perimeter is the 16 yellow stripes in the image below:

:https://assets.leetcode.com/uploads/2018/10/12/island.png" alt="island">
1
Unresolved directive in 0463-island-perimeter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0463_IslandPerimeter.java[]

464. Can I Win

In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins.

What if we change the game so that players cannot re-use integers?

For example, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a total >= 100.

Given an integer maxChoosableInteger and another integer desiredTotal, determine if the first player to move can force a win, assuming both players play optimally.

You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.

Example

Input:
maxChoosableInteger = 10
desiredTotal = 11

Output:
false

Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
1
Unresolved directive in 0464-can-i-win.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0464_CanIWin.java[]

465. Optimal Account Balancing

1
Unresolved directive in 0465-optimal-account-balancing.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0465_OptimalAccountBalancing.java[]

466. Count The Repetitions

Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc". On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”. You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.

Example:

Input:
s1="acb", n1=4
s2="ab", n2=2

Return:
2
1
Unresolved directive in 0466-count-the-repetitions.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0466_CountTheRepetitions.java[]

467. Unique Substrings in Wraparound String

Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s will look like this: "…​zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd…​.".

Now we have another string p. Your job is to find out how many unique non-empty substrings of p are present in s. In particular, your input is the string p and you need to output the number of different non-empty substrings of p in the string s.

Note: p consists of only lowercase English letters and the size of p might be over 10000.

Example 1:

Input: "a"
Output: 1

Explanation: Only the substring "a" of string "a" is in the string s.

Example 2:

Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in the string s.

Example 3:

Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string s.
1
Unresolved directive in 0467-unique-substrings-in-wraparound-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0467_UniqueSubstringsInWraparoundString.java[]

468. Validate IP Address

Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.

IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;

Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.

IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).

However, we don’t replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.

Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.

Note: You may assume there is no extra space or special characters in the input string.

Example 1:

Input: "172.16.254.1"

Output: "IPv4"

Explanation: This is a valid IPv4 address, return "IPv4".

Example 2:

Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"

Output: "IPv6"

Explanation: This is a valid IPv6 address, return "IPv6".

Example 3:

Input: "256.256.256.256"

Output: "Neither"

Explanation: This is neither a IPv4 address nor a IPv6 address.
1
Unresolved directive in 0468-validate-ip-address.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0468_ValidateIPAddress.java[]

469. Convex Polygon

1
Unresolved directive in 0469-convex-polygon.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0469_ConvexPolygon.java[]

470. Implement Rand10() Using Rand7()

Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.

Do NOT use system’s Math.random().

Example 1:

Input: 1
Output: [7]

Example 2:

Input: 2
Output: [8,4]

Example 3:

Input: 3
Output: [8,1,10]

Note:

  1. rand7 is predefined.

  2. Each testcase has one argument: n, the number of times that rand10 is called.

Follow up:

  1. What is the expected value for the number of calls to rand7() function?

  2. Could you minimize the number of calls to rand7()?

1
Unresolved directive in 0470-implement-rand10-using-rand7.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0470_ImplementRand10UsingRand7.java[]

471. Encode String with Shortest Length

1
Unresolved directive in 0471-encode-string-with-shortest-length.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0471_EncodeStringWithShortestLength.java[]

472. Concatenated Words

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

Example:

Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]

Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
               "dogcatsdog" can be concatenated by "dog", "cats" and "dog";
               "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

Note:

  1. The number of elements of the given array will not exceed `10,000 `

  2. The length sum of elements in the given array will not exceed 600,000.

  3. All the input string will only include lower case letters.

  4. The returned elements order does not matter.

1
Unresolved directive in 0472-concatenated-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0472_ConcatenatedWords.java[]

473. Matchsticks to Square

Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.</P>

Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.

Example 1:

Input: [1,1,2,2,2]
Output: true

Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.

Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.

Note:

  1. The length sum of the given matchsticks is in the range of 0 to 10^9.

  2. The length of the given matchstick array will not exceed 15.

1
Unresolved directive in 0473-matchsticks-to-square.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0473_MatchsticksToSquare.java[]

474. Ones and Zeroes

In the computer world, use restricted resource you have to generate maximum benefit is what we always want to pursue.

For now, suppose you are a dominator of m 0s and n 1s respectively. On the other hand, there is an array with strings consisting of only 0s and 1s.

Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s. Each 0 and 1 can be used at most once.

Note:

  1. The given numbers of 0s and 1s will both not exceed 100

  2. The size of given string array won’t exceed 600.

Example 1:

Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4

Explanation: This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are &ldquo;10,&rdquo;0001&rdquo;,&rdquo;1&rdquo;,&rdquo;0&rdquo;

Example 2:

Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2

Explanation: You could form "10", but then you'd have nothing left. Better form "0" and "1".
1
Unresolved directive in 0474-ones-and-zeroes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0474_OnesAndZeroes.java[]

475. Heaters

Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

  1. Numbers of houses and heaters you are given are non-negative and will not exceed 25000.

  2. Positions of houses and heaters you are given are non-negative and will not exceed 10^9.

  3. As long as a house is in the heaters' warm radius range, it can be warmed.

  4. All the heaters follow your radius standard and the warm radius will the same.

Example 1:

Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:

Input: [1,2,3,4],[1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
1
Unresolved directive in 0475-heaters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0475_Heaters.java[]

476. Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.

  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
1
Unresolved directive in 0476-number-complement.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0476_NumberComplement.java[]

477. Total Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Now your job is to find the total Hamming distance between all pairs of the given numbers.</p>

Example:

Input: 4, 14, 2

Output: 6

Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Note:

  1. Elements of the given array are in the range of 0 ` to `10^9

  2. Length of the array will not exceed 10^4.

1
Unresolved directive in 0477-total-hamming-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0477_TotalHammingDistance.java[]

478. Generate Random Point in a Circle

Given the radius and x-y positions of the center of a circle, write a function randPoint which generates a uniform random point in the circle.

Note:

  1. input and output values are in floating-point.

  2. radius and x-y position of the center of the circle is passed into the class constructor.

  3. a point on the circumference of the circle is considered to be in the circle.

  4. randPoint returns a size 2 array containing x-position and y-position of the random point, in that order.

Example 1:

Input:
 ["Solution","randPoint","randPoint","randPoint"]
 [[1,0,0],[],[],[]]
Output: [null,[-0.72939,-0.65505],[-0.78502,-0.28626],[-0.83119,-0.19803]]

Example 2:

Input:
 ["Solution","randPoint","randPoint","randPoint"]
 [[10,5,-7.5],[],[],[]]
Output: [null,[11.52438,-8.33273],[2.46992,-16.21705],[11.13430,-12.42337]]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution’s constructor has three arguments, the radius, x-position of the center, and y-position of the center of the circle. `randPoint has no arguments. Arguments are always wrapped with a list, even if there aren’t any.

1
Unresolved directive in 0478-generate-random-point-in-a-circle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0478_GenerateRandomPointInACircle.java[]

479. Largest Palindrome Product

Find the largest palindrome made from the product of two n-digit numbers.

Since the result could be very large, you should return the largest palindrome mod 1337.

Example:

Input: 2

Output: 987

Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

Note:

The range of n is [1,8].

1
Unresolved directive in 0479-largest-palindrome-product.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0479_LargestPalindromeProduct.java[]

480. Sliding Window Median

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examples:

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Your job is to output the median array for each window in the original array.

For example,

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Median
---------------               -----
[1  3  -1] -3  5  3  6  7       1
 1 [3  -1  -3] 5  3  6  7       -1
 1  3 [-1  -3  5] 3  6  7       -1
 1  3  -1 [-3  5  3] 6  7       3
 1  3  -1  -3 [5  3  6] 7       5
 1  3  -1  -3  5 [3  6  7]      6

Therefore, return the median sliding window as [1,-1,-1,3,5,6].

*Note: *

You may assume k is always valid, ie: k is always smaller than input array’s size for non-empty array.

Answers within 10^-5 of the actual value will be accepted as correct.

1
Unresolved directive in 0480-sliding-window-median.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0480_SlidingWindowMedian.java[]

481. Magical String

A magical string S consists of only '1' and '2' and obeys the following rules:

The string S is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string S itself.

The first few elements of string S is the following: S = "1221121221221121122……"

If we group the consecutive '1’s and '2’s in S, it will be:

1 22 11 2 1 22 1 22 11 2 11 22 …​…​

and the occurrences of '1’s or '2’s in each group are:

1 2 2 1 1 2 1 2 2 1 2 2 …​…​

You can see that the occurrence sequence above is the S itself.

Given an integer N as input, return the number of '1’s in the first N number in the magical string S.

Note: N will not exceed 100,000.

Example 1:

Input: 6
Output: 3
Explanation: The first 6 elements of magical string S is "12211" and it contains three 1's, so return 3.
1
Unresolved directive in 0481-magical-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0481_MagicalString.java[]

482. License Key Formatting

You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Given a non-empty string S and a number K, format the string according to the rules described above.

Example 1:

Input: S = "5F3Z-2e-9-w", K = 4

Output: "5F3Z-2E9W"

Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.

Example 2:

Input: S = "2-5g-3-J", K = 2

Output: "2-5G-3J"

Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.

Note:

  1. The length of string S will not exceed 12,000, and K is a positive integer.

  2. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).

  3. String S is non-empty.

1
Unresolved directive in 0482-license-key-formatting.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0482_LicenseKeyFormatting.java[]

483. Smallest Good Base

For an integer n, we call k>=2 a *good base* of n, if all digits of n base k are 1.

Now given a string representing n, you should return the smallest good base of n in string format.

Example 1:

Input: "13"
Output: "3"
Explanation: 13 base 3 is 111.

Example 2:

Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.

Example 3:

Input: "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.

Note:

  1. The range of n is [3, 10^18].

  2. The string representing n is always valid and will not have leading zeros.

1
Unresolved directive in 0483-smallest-good-base.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0483_SmallestGoodBase.java[]

484. Find Permutation

1
Unresolved directive in 0484-find-permutation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0484_FindPermutation.java[]

485. Max Consecutive Ones

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Note:

  1. The input array will only contain 0 and 1.

  2. The length of input array is a positive integer and will not exceed 10,000

1
Unresolved directive in 0485-max-consecutive-ones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0485_MaxConsecutiveOnes.java[]

486. Predict the Winner

Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.

Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.

Example 1:

Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. <br/>If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). <br/>So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. <br/>Hence, player 1 will never be the winner and you need to return False.

Example 2:

Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.

Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.

Note:

  1. 1 ⇐ length of the array ⇐ 20.

  2. Any scores in the given array are non-negative integers and will not exceed 10,000,000.

  3. If the scores of both players are equal, then player 1 is still the winner.

1
Unresolved directive in 0486-predict-the-winner.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0486_PredictTheWinner.java[]

487. Max Consecutive Ones II

1
Unresolved directive in 0487-max-consecutive-ones-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0487_MaxConsecutiveOnesII.java[]

488. Zuma Game

Think about Zuma Game. You have a row of balls on the table, colored red®, yellow(Y), blue(B), green(G), and white(W). You also have several balls in your hand.

Each time, you may choose a ball in your hand, and insert it into the row (including the leftmost place and rightmost place). Then, if there is a group of 3 or more balls in the same color touching, remove these balls. Keep doing this until no more balls can be removed.

Find the minimal balls you have to insert to remove all the balls on the table. If you cannot remove all the balls, output -1.

Example 1:

Input: board = "WRRBBW", hand = "RB"
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW

Example 2:

Input: board = "WWRRBBWW", hand = "WRBRW"
Output: 2
Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW -> empty

Example 3:

Input: board = "G", hand = "GGGGG"
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty

Example 4:

Input: board = "RBYYBBRRB", hand = "YRBGB"
Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B -> B[B] -> BB[B] -> empty

Constraints:

  • You may assume that the initial row of balls on the table won’t have any 3 or more consecutive balls with the same color.

  • The number of balls on the table won’t exceed 16, and the string represents these balls is called "board" in the input.

  • The number of balls in your hand won’t exceed 5, and the string represents these balls is called "hand" in the input.

  • Both input strings will be non-empty and only contain characters 'R','Y','B','G','W'.

1
Unresolved directive in 0488-zuma-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0488_ZumaGame.java[]

489. Robot Room Cleaner

1
Unresolved directive in 0489-robot-room-cleaner.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0489_RobotRoomCleaner.java[]

490. The Maze

1
Unresolved directive in 0490-the-maze.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0490_TheMaze.java[]

491. Increasing Subsequences

Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2.

Example:

Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

Note:

  1. The length of the given array will not exceed 15.

  2. The range of integer in the given array is [-100,100].

  3. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

1
Unresolved directive in 0491-increasing-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0491_IncreasingSubsequences.java[]

492. Construct the Rectangle

For a web developer, it is very important to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:

1. The area of the rectangular web page you designed must equal to the given target area.
2. The width W should not be larger than the length L, which means L >= W.
3. The difference between length L and width W should be as small as possible.

You need to output the length L and the width W of the web page you designed in sequence.

Example:

Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.

Note:

  1. The given area won’t exceed 10,000,000 and is a positive integer

  2. The web page’s width and length you designed must be positive integers.

1
Unresolved directive in 0492-construct-the-rectangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0492_ConstructTheRectangle.java[]

493. Reverse Pairs

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

You need to return the number of important reverse pairs in the given array.

Example1:

Input: [1,3,2,3,1]
Output: 2

Example2:

Input: [2,4,3,5,1]
Output: 3

Note:

  1. The length of the given array will not exceed 50,000.

  2. All the numbers in the input array are in the range of 32-bit integer.

1
Unresolved directive in 0493-reverse-pairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0493_ReversePairs.java[]

494. Target Sum

You are given a list of non-negative integers, a1, a2, …​, an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  1. The length of the given array is positive and will not exceed 20.

  2. The sum of elements in the given array will not exceed 1000.

  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

解题分析

这道题可以使用 DFS 解决。不过,需要注意的是,只需要保存关键变量即可。另外,也可以增加实例变量。

思考题

  1. 再推敲一下动态规划的解法;

  2. 学习背包问题!

参考资料

You are given a list of non-negative integers, a1, a2, …​, an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target 3.

Note:

  1. The length of the given array is positive and will not exceed 20.

  2. The sum of elements in the given array will not exceed 1000.

  3. Your output answer is guaranteed to be fitted in a 32-bit integer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.diguage.algorithm.leetcode;

import java.util.Objects;

/**
 * = 494. Target Sum
 *
 * https://leetcode.com/problems/target-sum/[Target Sum - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 21:59
 */
public class _0494_TargetSum {
    /**
     * Runtime: 3 ms, faster than 90.55% of Java online submissions for Target Sum.
     * Memory Usage: 38.8 MB, less than 10.00% of Java online submissions for Target Sum.
     *
     * Copy from: https://leetcode-cn.com/problems/target-sum/solution/dong-tai-gui-hua-ji-bai-liao-98de-javayong-hu-by-r/[动态规划击败了98%的java用户 - 目标和 - 力扣(LeetCode)]
     */
    public int findTargetSumWays(int[] nums, int S) {
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        if (sum < S || (sum + S) % 2 == 1) {
            return 0;
        }
        int target = (sum + S) / 2;
        int[] dp = new int[target + 1];
        dp[0] = 1;
        for (int num : nums) {
            for (int i = target; i >= num; i--) {
                dp[i] += dp[i - num];
            }
        }
        return dp[target];
    }

    /**
     * Runtime: 688 ms, faster than 5.06% of Java online submissions for Target Sum.
     * Memory Usage: 39 MB, less than 10.00% of Java online submissions for Target Sum.
     */
    private int count = 0;

    public int findTargetSumWaysDfs(int[] nums, int S) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        findTargetSumWays(nums, S, 0, 0);
        return count;
    }

    private void findTargetSumWays(int[] nums, int target, int sum, int index) {
        if (index == nums.length) {
            if (sum == target) {
                count++;
            }
        } else {
            int num = nums[index];
            findTargetSumWays(nums, target, sum + num, index + 1);
            findTargetSumWays(nums, target, sum - num, index + 1);
        }
    }

    public static void main(String[] args) {
        _0494_TargetSum solution = new _0494_TargetSum();
        int[] n1 = {1, 1, 1, 1, 1};
        int r1 = solution.findTargetSumWays(n1, 3);
        System.out.println((r1 == 5) + " : " + r1);
    }
}

495. Teemo Attacking

In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo’s attacking ascending time series towards Ashe and the poisoning time duration per Teemo’s attacking, you need to output the total time that Ashe is in poisoned condition.

You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.

Example 1:

Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately.
This poisoned status will last 2 seconds until the end of time point 2.
And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
So you finally need to output 4.

Example 2:

Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned.
This poisoned status will last 2 seconds until the end of time point 2.
However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
So you finally need to output 3.

Note:

  1. You may assume the length of given time series array won’t exceed 10000.

  2. You may assume the numbers in the Teemo’s attacking time series and his poisoning time duration per attacking are non-negative integers, which won’t exceed 10,000,000.

1
Unresolved directive in 0495-teemo-attacking.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0495_TeemoAttacking.java[]

496. Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of `nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  1. All elements in nums1 and nums2 are unique.

  2. The length of both nums1 and nums2 would not exceed 1000.

1
Unresolved directive in 0496-next-greater-element-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0496_NextGreaterElementI.java[]

497. Random Point in Non-overlapping Rectangles

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:

Input:
 ["Solution","pick","pick","pick"]
 [[[[1,1,5,5]]],[],[],[]]
Output: [null,[4,1],[4,1],[3,3]]

Example 2:

Input:
 ["Solution","pick","pick","pick","pick","pick"]
 [[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]
Output:
 [null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-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
Unresolved directive in 0497-random-point-in-non-overlapping-rectangles.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0497_RandomPointInNonOverlappingRectangles.java[]

498. Diagonal Traverse

Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.

Example:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

Output:  [1,2,4,7,5,3,6,8,9]

Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/diagonal_traverse.png" alt="diagonal traverse">

Note:

The total number of elements of the given matrix will not exceed 10,000.

1
Unresolved directive in 0498-diagonal-traverse.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0498_DiagonalTraverse.java[]

499. The Maze III

1
Unresolved directive in 0499-the-maze-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0499_TheMazeIII.java[]

500. Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.

keyboard

Example:

Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.

  2. You may assume the input string will only contain letters of alphabet.

1
Unresolved directive in 0500-keyboard-row.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0500_KeyboardRow.java[]

501. Find Mode in Binary Search Tree

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node’s key.

  • The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.

  • Both the left and right subtrees must also be binary search trees.

For example:

Given BST [1,null,2,2],

   1
    \
     2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

1
Unresolved directive in 0501-find-mode-in-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0501_FindModeInBinarySearchTree.java[]

502. IPO

Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.

You are given several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.

To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital.

Example 1:

Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].

Output: 4

Explanation: Since your initial capital is 0, you can only start the project indexed 0.
             After finishing it you will obtain profit 1 and your capital becomes 1.
             With capital 1, you can either start the project indexed 1 or the project indexed 2.
             Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
             Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.

Note:

  1. You may assume all numbers in the input are non-negative integers.

  2. The length of Profits array and Capital array will not exceed 50,000.

  3. The answer is guaranteed to fit in a 32-bit signed integer.

1
Unresolved directive in 0502-ipo.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0502_IPO.java[]

503. Next Greater Element II

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, output -1 for this number.

Example 1:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; </br>The number 2 can't find next greater number; </br>The second 1's next greater number needs to search circularly, which is also 2.

Note: The length of given array won’t exceed 10000.

1
Unresolved directive in 0503-next-greater-element-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0503_NextGreaterElementII.java[]

504. Base 7

Given an integer, return its base 7 string representation.

Example 1:

Input: 100
Output: "202"

Example 2:

Input: -7
Output: "-10"

Note: The input will be in range of [-1e7, 1e7].

1
Unresolved directive in 0504-base-7.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0504_Base7.java[]

505. The Maze II

1
Unresolved directive in 0505-the-maze-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0505_TheMazeII.java[]

506. Relative Ranks

Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".

Example 1:

Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". <br/>For the left two athletes, you just need to output their relative ranks according to their scores.

Note:

  1. N is a positive integer and won’t exceed 10,000.

  2. All the scores of athletes are guaranteed to be unique.

1
Unresolved directive in 0506-relative-ranks.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0506_RelativeRanks.java[]

507. Perfect Number

We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.

Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.

Example:

Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14

Note: The input number n will not exceed 100,000,000. (1e8)

1
Unresolved directive in 0507-perfect-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0507_PerfectNumber.java[]

508. Most Frequent Subtree Sum

Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1 Input:

  5
 /  \
2   -3

return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2 Input:

  5
 /  \
2   -5

return [2], since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

1
Unresolved directive in 0508-most-frequent-subtree-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0508_MostFrequentSubtreeSum.java[]

509. Fibonacci Number

The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.

Given N, calculate F(N).

Example 1:

Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.

Example 2:

Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.

Example 3:

Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.

Note:

0 ≤ N ≤ 30.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.diguage.algorithm.leetcode;

/**
 * = 509. Fibonacci Number
 *
 * https://leetcode.com/problems/fibonacci-number/[Fibonacci Number - LeetCode^]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-04-25 22:06
 */
public class _0509_FibonacciNumber {
    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Fibonacci Number.
     * Memory Usage: 36.3 MB, less than 5.51% of Java online submissions for Fibonacci Number.
     */
    public int fib(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        int i1 = 0;
        int i2 = 1;
        for (int i = 2; i <= n; i++) {
            if (i1 <= i2) {
                i1 += i2;
            } else {
                i2 += i1;
            }
        }
        return Math.max(i1, i2);
    }
}

510. Inorder Successor in BST II

1
Unresolved directive in 0510-inorder-successor-in-bst-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0510_InorderSuccessorInBSTII.java[]

511. Game Play Analysis I

1
Unresolved directive in 0511-game-play-analysis-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0511_GamePlayAnalysisI.java[]

512. Game Play Analysis II

1
Unresolved directive in 0512-game-play-analysis-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0512_GamePlayAnalysisII.java[]

513. Find Bottom Left Tree Value

Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2:

Input:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Note: You may assume the tree (i.e., the given root node) is not NULL.

1
Unresolved directive in 0513-find-bottom-left-tree-value.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0513_FindBottomLeftTreeValue.java[]

514. Freedom Trail

In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.

Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.

Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button.

At the stage of rotating the ring to spell the key character key[i]:

  1. You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring’s characters at the 12:00 direction, where this character must equal to the character key[i].

  2. If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you’ve finished all the spelling.

Example:

ring
Input: ring = "godding", key = "gd"
Output: 4
Explanation:
For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
Also, we need 1 more step for spelling.
So the final output is 4.

Note:

  1. Length of both ring and key will be in range 1 to 100.

  2. There are only lowercase letters in both strings and might be some duplcate characters in both strings.

  3. It’s guaranteed that string key could always be spelled by rotating the string ring.

1
Unresolved directive in 0514-freedom-trail.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0514_FreedomTrail.java[]

515. Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.

Example:

Input:

          1
         / \
        3   2
       / \   \
      5   3   9

Output: [1, 3, 9]
1
Unresolved directive in 0515-find-largest-value-in-each-tree-row.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0515_FindLargestValueInEachTreeRow.java[]

516. Longest Palindromic Subsequence

Given a string s, find the longest palindromic subsequence’s length in s. You may assume that the maximum length of s is 1000.

Example 1: Input:

"bbbab"

Output:

4

One possible longest palindromic subsequence is "bbbb".

Example 2: Input:

"cbbd"

Output:

2

One possible longest palindromic subsequence is "bb".

1
Unresolved directive in 0516-longest-palindromic-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0516_LongestPalindromicSubsequence.java[]

517. Super Washing Machines

You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.

For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines * at the same time *.

Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.

Example1

Input: [1,0,5]

Output: 3

Explanation:
1st move:    1     0 <-- 5    =>    1     1     4
2nd move:    1 <-- 1 <-- 4    =>    2     1     3
3rd move:    2     1 <-- 3    =>    2     2     2

Example2

Input: [0,3,0]

Output: 2

Explanation:
1st move:    0 <-- 3     0    =>    1     2     0
2nd move:    1     2 --> 0    =>    1     1     1

Example3

Input: [0,2,0]

Output: -1

Explanation:
It's impossible to make all the three washing machines have the same number of dresses.

Note:

  1. The range of n is [1, 10000].

  2. The range of dresses number in a super washing machine is [0, 1e5].

1
Unresolved directive in 0517-super-washing-machines.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0517_SuperWashingMachines.java[]

518. Coin Change 2

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

Example 1:

Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3:

Input: amount = 10, coins = [10]
Output: 1

Note:

You can assume that

  • 0 ⇐ amount ⇐ 5000

  • 1 ⇐ coin ⇐ 5000

  • the number of coins is less than 500

  • the answer is guaranteed to fit into signed 32-bit integer

1
Unresolved directive in 0518-coin-change-2.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0518_CoinChange2.java[]

519. Random Flip Matrix

You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix where all values are initially 0. Write a function flip which chooses a 0 value uniformly at random, changes it to 1, and then returns the position [row.id, col.id] of that value. Also, write a function reset which sets all values back to 0. Try to minimize the number of calls to system’s Math.random() and optimize the time and space complexity.

Note:

  1. 1 ⇐ n_rows, n_cols ⇐ 10000

  2. 0 ⇐ row.id < n_rows and 0 ⇐ col.id < n_cols

  3. flip will not be called when the matrix has no 0 values left.

  4. the total number of calls to flip and reset will not exceed 1000.

Example 1:

Input:
 ["Solution","flip","flip","flip","flip"]
 [[2,3],[],[],[],[]]
Output: [null,[0,1],[1,2],[1,0],[1,1]]

Example 2:

Input:
 ["Solution","flip","flip","reset","flip"]
 [[1,2],[],[],[],[]]
Output: [null,[0,0],[0,1],null,[0,0]]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution’s constructor has two arguments, `n_rows and n_cols. flip and reset have no arguments. Arguments are always wrapped with a list, even if there aren’t any.

1
Unresolved directive in 0519-random-flip-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0519_RandomFlipMatrix.java[]

520. Detect Capital

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

  1. All letters in this word are capitals, like "USA".

  2. All letters in this word are not capitals, like "leetcode".

  3. Only the first letter in this word is capital, like "Google".

Otherwise, we define that this word doesn’t use capitals in a right way.

Example 1:

Input: "USA"
Output: True

Example 2:

Input: "FlaG"
Output: False

Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

1
Unresolved directive in 0520-detect-capital.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0520_DetectCapital.java[]

521. Longest Uncommon Subsequence I

Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:

Input: "aba", "cdc"
Output: 3
Explanation: The longest uncommon subsequence is "aba" (or "cdc"), <br/>because "aba" is a subsequence of "aba", <br/>but not a subsequence of any other strings in the group of two strings.

Note:

  1. Both strings' lengths will not exceed 100.

  2. Only letters from a ~ z will appear in input strings.

1
Unresolved directive in 0521-longest-uncommon-subsequence-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0521_LongestUncommonSubsequenceI.java[]

522. Longest Uncommon Subsequence II

Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:

Input: "aba", "cdc", "eae"
Output: 3

Note:

  1. All the given strings' lengths will not exceed 10.

  2. The length of the given list will be in the range of [2, 50].

1
Unresolved directive in 0522-longest-uncommon-subsequence-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0522_LongestUncommonSubsequenceII.java[]

523. Continuous Subarray Sum

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Example 2:

Input: [23, 2, 6, 4, 7],  k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

Note:

  1. The length of the array won’t exceed 10,000.

  2. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

1
Unresolved directive in 0523-continuous-subarray-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0523_ContinuousSubarraySum.java[]

524. Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"

Example 2:

Input:
s = "abpcplea", d = ["a","b","c"]

Output:
"a"

Note:

  1. All the strings in the input will only contain lower-case letters.

  2. The size of the dictionary won’t exceed 1,000.

  3. The length of all the strings in the input won’t exceed 1,000.

1
Unresolved directive in 0524-longest-word-in-dictionary-through-deleting.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0524_LongestWordInDictionaryThroughDeleting.java[]

525. Contiguous Array

Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.

Example 1:

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Note: The length of the given binary array will not exceed 50,000.

1
Unresolved directive in 0525-contiguous-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0525_ContiguousArray.java[]

526. Beautiful Arrangement

Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is constructed by these N numbers successfully if one of the following is true for the ith position (1 ⇐ i ⇐ N) in this array:

  1. The number at the ith position is divisible by i.

  2. i is divisible by the number at the ith position.

Now given N, how many beautiful arrangements can you construct?

Example 1:

Input: 2
Output: 2
Explanation:

The first beautiful arrangement is [1, 2]:

Number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1).

Number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2).

The second beautiful arrangement is [2, 1]:

Number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1).

Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.

Note:

  1. N is a positive integer and will not exceed 15.

1
Unresolved directive in 0526-beautiful-arrangement.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0526_BeautifulArrangement.java[]

527. Word Abbreviation

1
Unresolved directive in 0527-word-abbreviation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0527_WordAbbreviation.java[]

528. Random Pick with Weight

Given an array w of positive integers, where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.

Note:

  1. 1 ⇐ w.length ⇐ 10000

  2. 1 ⇐ w[i] ⇐ 10^5

  3. pickIndex will be called at most 10000 times.

Example 1:

Input:
 ["Solution","pickIndex"]
 [[[1]],[]]
Output: [null,0]

Example 2:

Input:
 ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]
 [[[1,3]],[],[],[],[],[]]
Output: [null,0,1,1,1,0]

Explanation of Input Syntax:

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

1
Unresolved directive in 0528-random-pick-with-weight.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0528_RandomPickWithWeight.java[]

529. Minesweeper

Let’s play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)">Wikipedia</a>, <a href="http://minesweeperonline.com">online game</a>)!

You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine.

Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules:

  1. If a mine ('M') is revealed, then the game is over - change it to 'X'.

  2. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively.

  3. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.

  4. Return the board when no more squares will be revealed.

Example 1:

Input:

[['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'M', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E']]

Click : [3,0]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" alt="minesweeper example 1">

Example 2:

Input:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

Click : [1,2]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'X', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" alt="minesweeper example 2">

Note:

  1. The range of the input matrix’s height and width is [1,50].

  2. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square.

  3. The input board won’t be a stage when game is over (some mines have been revealed).

  4. For simplicity, not mentioned rules should be ignored in this problem. For example, you don’t need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.

1
Unresolved directive in 0529-minesweeper.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0529_Minesweeper.java[]

530. Minimum Absolute Difference in BST

Given a binary search tree with non-negative values, find the minimum <a href="https://en.wikipedia.org/wiki/Absolute_difference">absolute difference</a> between values of any two nodes.

Example:

Input:

   1
    \
     3
    /
   2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

Note: There are at least two nodes in this BST.

1
Unresolved directive in 0530-minimum-absolute-difference-in-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0530_MinimumAbsoluteDifferenceInBST.java[]

531. Lonely Pixel I

1
Unresolved directive in 0531-lonely-pixel-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0531_LonelyPixelI.java[]

532. K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their <a href = "https://en.wikipedia.org/wiki/Absolute_difference">absolute difference</a> is k.

Example 1:

Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).</br>Although we have two 1s in the input, we should only return the number of unique pairs.

Example 2:

Input: [1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).

Example 3:

Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).

Note:

  1. The pairs (i, j) and (j, i) count as the same pair.

  2. The length of the array won’t exceed 10,000.

  3. All the integers in the given input belong to the range: [-1e7, 1e7].

1
Unresolved directive in 0532-k-diff-pairs-in-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0532_KDiffPairsInAnArray.java[]

533. Lonely Pixel II

1
Unresolved directive in 0533-lonely-pixel-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0533_LonelyPixelII.java[]

534. Game Play Analysis III

1
Unresolved directive in 0534-game-play-analysis-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0534_GamePlayAnalysisIII.java[]

535. Encode and Decode TinyURL

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

1
Unresolved directive in 0535-encode-and-decode-tinyurl.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0535_EncodeAndDecodeTinyURL.java[]

536. Construct Binary Tree from String

1
Unresolved directive in 0536-construct-binary-tree-from-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0536_ConstructBinaryTreeFromString.java[]

537. Complex Number Multiplication

Given two strings representing two <a href = "https://en.wikipedia.org/wiki/Complex_number">complex numbers</a>.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i)  (1 + i) = 1 + i^2^ + 2  i = 2i, and you need convert it to the form of 0+2i.

Example 2:

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i)  (1 - i) = 1 + i^2^ - 2  i = -2i, and you need convert it to the form of 0+-2i.

Note:

  1. The input strings will not have extra blank.

  2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

1
Unresolved directive in 0537-complex-number-multiplication.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0537_ComplexNumberMultiplication.java[]

538. Convert BST to Greater Tree

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13
1
Unresolved directive in 0538-convert-bst-to-greater-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0538_ConvertBSTToGreaterTree.java[]

539. Minimum Time Difference

Given a list of 24-hour clock time points in "Hour:Minutes" format, find the minimum minutes difference between any two time points in the list.

Example 1:

Input: ["23:59","00:00"]
Output: 1

Note:

  1. The number of time points in the given list is at least 2 and won’t exceed 20000.

  2. The input time is legal and ranges from 00:00 to 23:59.

1
Unresolved directive in 0539-minimum-time-difference.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0539_MinimumTimeDifference.java[]

540. Single Element in a Sorted Array

You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Find this single element that appears only once.

Example 1:

Input: [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2:

Input: [3,3,7,7,10,11,11]
Output: 10

Note: Your solution should run in O(log n) time and O(1) space.

1
Unresolved directive in 0540-single-element-in-a-sorted-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0540_SingleElementInASortedArray.java[]

541. Reverse String II

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Restrictions: *

  1. The string consists of lower English letters only.

  2. Length of the given string and k will in the range [1, 10000]

1
Unresolved directive in 0541-reverse-string-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0541_ReverseStringII.java[]

542. 01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

*Example 1: *

Input:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

Output:
[[0,0,0],
 [0,1,0],
 [0,0,0]]

*Example 2: *

Input:
[[0,0,0],
 [0,1,0],
 [1,1,1]]

Output:
[[0,0,0],
 [0,1,0],
 [1,2,1]]

Note:

  1. The number of elements of the given matrix will not exceed 10,000.

  2. There are at least one 0 in the given matrix.

  3. The cells are adjacent in only four directions: up, down, left and right.

1
Unresolved directive in 0542-01-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0542_01Matrix.java[]

543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree
        1
       / \
      2   3
     / \
    4   5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解题分析

这道题就是一个深度优先搜索。不同之处在于,要在遍历过程中,把直径的最大值保存下来。同时,还要返回子树中最长的路径。

参考资料

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:

Given a binary tree

          1
         / \
        2   3
       / \
      4   5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 543. Diameter of Binary Tree
 *
 * https://leetcode.com/problems/diameter-of-binary-tree/[Diameter of Binary Tree - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 23:31
 */
public class _0543_DiameterOfBinaryTree {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Diameter of Binary Tree.
     * Memory Usage: 39 MB, less than 19.48% of Java online submissions for Diameter of Binary Tree.
     */
    private int result;
    public int diameterOfBinaryTree(TreeNode root) {
        result = 1;
        dfs(root);
        return result - 1;
    }

    private int dfs(TreeNode root) {
        if (Objects.isNull(root)) {
            return 0;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        result = Math.max(result, left + right + 1);
        return Math.max(left, right) + 1;
    }

    public static void main(String[] args) {
        _0543_DiameterOfBinaryTree solution = new _0543_DiameterOfBinaryTree();
        int r1 = solution.diameterOfBinaryTree(buildTree(asList(1, 2, 3, 4, 5)));
        System.out.println((r1 == 3) + " : " + r1);
    }
}

544. Output Contest Matches

1
Unresolved directive in 0544-output-contest-matches.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0544_OutputContestMatches.java[]

545. Boundary of Binary Tree

1
Unresolved directive in 0545-boundary-of-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0545_BoundaryOfBinaryTree.java[]

546. Remove Boxes

Given several boxes with different colors represented by different positive numbers.

You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k points.

Find the maximum points you can get.

Example 1: Input:

[1, 3, 2, 2, 2, 3, 4, 3, 1]

Output:

23

Explanation:

[1, 3, 2, 2, 2, 3, 4, 3, 1]
----> [1, 3, 3, 4, 3, 1] (33=9 points)
----> [1, 3, 3, 3, 1] (11=1 points)
----> [1, 1] (33=9 points)
----> [] (22=4 points)

Note: The number of boxes n would not exceed 100.

1
Unresolved directive in 0546-remove-boxes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0546_RemoveBoxes.java[]

547. Friend Circles

There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends.

Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.

Example 1:

Input:
[[1,1,0],
 [1,1,0],
 [0,0,1]]
Output: 2
Explanation: The 0~th~ and 1~st~ students are direct friends, so they are in a friend circle. <br/>The 2~nd~ student himself is in a friend circle. So return 2.

Example 2:

Input:
[[1,1,0],
 [1,1,1],
 [0,1,1]]
Output: 1
Explanation: The 0~th~ and 1~st~ students are direct friends, the 1~st~ and 2~nd~ students are direct friends, <br/>so the 0~th~ and 2~nd~ students are indirect friends. All of them are in the same friend circle, so return 1.

Note:

  1. N is in range [1,200].

  2. M[i][i] = 1 for all students.

  3. If M[i][j] = 1, then M[j][i] = 1.

1
Unresolved directive in 0547-friend-circles.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0547_FriendCircles.java[]

548. Split Array with Equal Sum

1
Unresolved directive in 0548-split-array-with-equal-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0548_SplitArrayWithEqualSum.java[]

549. Binary Tree Longest Consecutive Sequence II

1
Unresolved directive in 0549-binary-tree-longest-consecutive-sequence-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0549_BinaryTreeLongestConsecutiveSequenceII.java[]

550. Game Play Analysis IV

1
Unresolved directive in 0550-game-play-analysis-iv.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0550_GamePlayAnalysisIV.java[]

551. Student Attendance Record I

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. 'A' : Absent.

  2. 'L' : Late.

  3. 'P' : Present.

A student could be rewarded if his attendance record doesn’t contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False
1
Unresolved directive in 0551-student-attendance-record-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0551_StudentAttendanceRecordI.java[]

552. Student Attendance Record II

Given a positive integer n, return the number of all possible attendance records with length n, which will be regarded as rewardable. The answer may be very large, return it after mod 109 + 7.

A student attendance record is a string that only contains the following three characters:

  1. 'A' : Absent.

  2. 'L' : Late.

  3. 'P' : Present.

A record is regarded as rewardable if it doesn’t contain more than one 'A' (absent) or more than two continuous 'L' (late).

Example 1:

Input: n = 2
Output: 8
Explanation:
There are 8 records with length 2 will be regarded as rewardable:
"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
Only "AA" won't be regarded as rewardable owing to more than one absent times.

Note: The value of n won’t exceed 100,000.

1
Unresolved directive in 0552-student-attendance-record-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0552_StudentAttendanceRecordII.java[]

553. Optimal Division

Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] → 2 / 3 / 4.

However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corresponding expression in string format. Your expression should NOT contain redundant parenthesis.

Example:

Input: [1000,100,10,2]
Output: "1000/(100/10/2)"
Explanation:
1000/(100/10/2) = 1000/100/10)/2) = 200 However, the bold parenthesis in "1000/((*100/10)*/2)" are redundant, <br/>since they don't influence the operation priority. So you should return "1000/(100/10/2)".  Other cases: 1000/(100/10)/2 = 50 1000/(100/(10/2 = 50
1000/100/10/2 = 0.5
1000/100/(10/2) = 2

Note:

  1. The length of the input array is [1, 10].

  2. Elements in the given array will be in range [2, 1000].

  3. There is only one optimal division for each test case.

1
Unresolved directive in 0553-optimal-division.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0553_OptimalDivision.java[]

554. Brick Wall

There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. You want to draw a vertical line from the top to the bottom and cross the least bricks.

The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.

If your line go through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.

*You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. *

Example:

Input: [[1,2,2,1],
        [3,1,2],
        [1,3,2],
        [2,4],
        [3,1,2],
        [1,3,1,1]]

Output: 2

Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/brick_wall.png" alt="brick wall">

Note:

  1. The width sum of bricks in different rows are the same and won’t exceed INT_MAX.

  2. The number of bricks in each row is in range [1,10,000]. The height of wall is in range [1,10,000]. Total number of bricks of the wall won’t exceed 20,000.

1
Unresolved directive in 0554-brick-wall.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0554_BrickWall.java[]

555. Split Concatenated Strings

1
Unresolved directive in 0555-split-concatenated-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0555_SplitConcatenatedStrings.java[]

556. Next Greater Element III

Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1
1
Unresolved directive in 0556-next-greater-element-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0556_NextGreaterElementIII.java[]

557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

1
Unresolved directive in 0557-reverse-words-in-a-string-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0557_ReverseWordsInAStringIII.java[]

558. Quad Tree Intersection

A quadtree is a tree data in which each internal node has exactly four children: topLeft, topRight, bottomLeft and bottomRight. Quad trees are often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions.

We want to store True/False information in our quad tree. The quad tree is used to represent a N * N boolean grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same. Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.

For example, below are two quad trees A and B:

A:
--------------+   T: true
|       |       |   F: false
|   T   |   T   |
|       |       |
--------------+
|       |       |
|   F   |   F   |
|       |       |
--------------+
topLeft: T
topRight: T
bottomLeft: F
bottomRight: F

B:
-------------
|       | F | F |
|   T   ------+
|       | T | T |
-------------
|       |       |
|   T   |   F   |
|       |       |
--------------+
topLeft: T
topRight:
     topLeft: F
     topRight: F
     bottomLeft: T
     bottomRight: T
bottomLeft: T
bottomRight: F

Your task is to implement a function that will take two quadtrees and return a quadtree that represents the logical OR (or union) of the two trees.

A:                 B:                 C (A or B):
--------------+  -------------  --------------+
|       |       |  |       | F | F |  |       |       |
|   T   |   T   |  |   T   ------+  |   T   |   T   |
|       |       |  |       | T | T |  |       |       |
--------------+  -------------  --------------+
|       |       |  |       |       |  |       |       |
|   F   |   F   |  |   T   |   F   |  |   T   |   F   |
|       |       |  |       |       |  |       |       |
--------------+  --------------+  --------------+

Note:

  1. Both A and B represent grids of size N * N.

  2. N is guaranteed to be a power of 2.

  3. If you want to know more about the quad tree, you can refer to its <a href="https://en.wikipedia.org/wiki/Quadtree">wiki</a>.

  4. The logic OR operation is defined as this: "A or B" is true if A is true, or if B is true, or if both A and B are true.

1
Unresolved directive in 0558-quad-tree-intersection.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0558_QuadTreeIntersection.java[]

559. Maximum Depth of N-ary Tree

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Example 1:

narytreeexample
Input: root = [1,null,3,2,4,null,5,6]
Output: 3

Example 2:

sample 4 964
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 5

Constraints:

  • The depth of the n-ary tree is less than or equal to 1000.

  • The total number of nodes is between [0, 10^4].

1
Unresolved directive in 0559-maximum-depth-of-n-ary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0559_MaximumDepthOfNAryTree.java[]

560. Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input: nums = [1,1,1], k = 2
Output: 2

Note:

  1. The length of the array is in range [1, 20,000].

  2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

解题分析

背后的想法如下:如果累积总和(由 sum[i] 表示加到 ith 的和)最多两个指数是相同的,那么这些元素之间的元素总和为零。进一步扩展相同的想法,如果累计总和,在索引 ij 处相差 k,即 sum[i]−sum[j]=k,则位于索引 ij 之间的元素之和是 k

基于这些想法,可以使用了一个哈希表 map,它用于存储所有可能的索引的累积总和以及相同累加和发生的次数。我们以以下形式存储数据:(sumisumi 的出现次数)。我们遍历数组 nums 并继续寻找累积总和。每当我们遇到一个新的和时,我们在 map 中创建一个与该总和相对应的新条目。如果再次出现相同的和,我们增加与 map 中的和相对应的计数。此外,对于遇到的每个总和,我们还确定已经发生 sum - k 总和的次数,因为它将确定具有总和 k 的子阵列发生到当前索引的次数。我们将 count 增加相同的量。

在完成遍历数组后,count 记录了所需结果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 560. Subarray Sum Equals K
 *
 * https://leetcode.com/problems/subarray-sum-equals-k/[Subarray Sum Equals K - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 23:14
 */
public class _0560_SubarraySumEqualsK {
    /**
     * Runtime: 12 ms, faster than 97.62% of Java online submissions for Subarray Sum Equals K.
     * Memory Usage: 42.2 MB, less than 5.43% of Java online submissions for Subarray Sum Equals K.
     *
     * Copy from: https://leetcode-cn.com/problems/subarray-sum-equals-k/solution/he-wei-kde-zi-shu-zu-by-leetcode/[和为K的子数组 - 和为K的子数组 - 力扣(LeetCode)]
     */
    public int subarraySum(int[] nums, int k) {
        if (Objects.isNull(nums) || nums.length == 0) {
            return 0;
        }
        int count = 0, sum = 0;
        Map<Integer, Integer> sumToCountMap = new HashMap<>();
        sumToCountMap.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (sumToCountMap.containsKey(sum - k)) {
                count += sumToCountMap.get(sum - k);
            }
            sumToCountMap.put(sum, sumToCountMap.getOrDefault(sum, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        _0560_SubarraySumEqualsK solution = new _0560_SubarraySumEqualsK();

        int[] n4 = {3, 4, 7, 2, -3, 1, 4, 2};
        int r4 = solution.subarraySum(n4, 7);
        System.out.println((r4 == 4) + " : " + r4);

        int[] n3 = {1};
        int r3 = solution.subarraySum(n3, 0);
        System.out.println((r3 == 0) + " : " + r3);

        int[] n2 = {-1, -1, 1};
        int r2 = solution.subarraySum(n2, 0);
        System.out.println((r2 == 1) + " : " + r2);

        int[] n1 = {1, 1, 1};
        int r1 = solution.subarraySum(n1, 2);
        System.out.println((r1 == 2) + " : " + r1);
    }
}

这个方法是基于一个idea:sum[j] - sum[i] == k 的话,nums[i, j ] 之间数字的和就是 k

561. Array Partition I

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …​, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

Note:

  1. n is a positive integer, which is in the range of [1, 10000].

  2. All the integers in the array will be in the range of [-10000, 10000].

1
Unresolved directive in 0561-array-partition-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0561_ArrayPartitionI.java[]

562. Longest Line of Consecutive One in Matrix

1
Unresolved directive in 0562-longest-line-of-consecutive-one-in-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0562_LongestLineOfConsecutiveOneInMatrix.java[]

563. Binary Tree Tilt

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

Example:

Input:
         1
       /   \
      2     3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note:

  1. The sum of node values in any subtree won’t exceed the range of 32-bit integer.

  2. All the tilt values won’t exceed the range of 32-bit integer.

1
Unresolved directive in 0563-binary-tree-tilt.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0563_BinaryTreeTilt.java[]

564. Find the Closest Palindrome

Given an integer n, find the closest integer (not including itself), which is a palindrome.

The 'closest' is defined as absolute difference minimized between two integers.

Example 1:

Input: "123"
Output: "121"

Note:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.

  2. If there is a tie, return the smaller one as answer.

1
Unresolved directive in 0564-find-the-closest-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0564_FindTheClosestPalindrome.java[]

565. Array Nesting

A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], …​ } subjected to the rule below.

Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S.

Example 1:

Input: A = [5,4,0,3,1,6,2]
Output: 4
Explanation:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.

One of the longest S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}

Note:

  1. N is an integer within the range [1, 20,000].

  2. The elements of A are all distinct.

  3. Each element of A is an integer within the range [0, N-1].

1
Unresolved directive in 0565-array-nesting.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0565_ArrayNesting.java[]

566. Reshape the Matrix

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same *row-traversing* order as they were.

If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:

Input:
nums =
[[1,2],
 [3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example 2:

Input:
nums =
[[1,2],
 [3,4]]
r = 2, c = 4
Output:
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2  2 matrix to a 2  4 matrix. So output the original matrix.

Note:

  1. The height and width of the given matrix is in range [1, 100].

  2. The given r and c are all positive.

1
Unresolved directive in 0566-reshape-the-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0566_ReshapeTheMatrix.java[]

567. Permutation in String

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.

Example 1:
Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input:s1= "ab" s2 = "eidboaoo"
Output: False

Note:

  • The input strings only contain lower case letters.

  • The length of both given strings is in range [1, 10,000].

解题分析

滑动窗口大法好!

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.

Example 1:

Input: s1 = "ab" s2 = "eidbaooo"
Output: True
Explanation: s2 contains one permutation of s1 ("ba").

Example 2:

Input: s1= "ab" s2 = "eidboaoo"
Output: False

Note:

  1. The input strings only contain lower case letters.

  2. The length of both given strings is in range [1, 10,000].

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 567. Permutation in String
 *
 * https://leetcode.com/problems/permutation-in-string/[Permutation in String - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 18:05
 */
public class _0567_PermutationInString {
    /**
     * Runtime: 14 ms, faster than 45.41% of Java online submissions for Permutation in String.
     * Memory Usage: 39.4 MB, less than 7.69% of Java online submissions for Permutation in String.
     */
    public boolean checkInclusion(String s1, String s2) {
        if (Objects.isNull(s1) || s1.length() == 0) {
            return true;
        }
        if (Objects.isNull(s2) || s2.length() == 0 || s2.length() < s1.length()) {
            return false;
        }
        Map<Character, Integer> needs = new HashMap<>();
        for (char c : s1.toCharArray()) {
            needs.put(c, needs.getOrDefault(c, 0) + 1);
        }
        int left = 0, right = 0;
        int match = 0;
        Map<Character, Integer> windows = new HashMap<>();
        while (right < s2.length()) {
            char rChar = s2.charAt(right);
            if (needs.containsKey(rChar)) {
                int rCount = windows.getOrDefault(rChar, 0) + 1;
                windows.put(rChar, rCount);
                if (rCount == needs.get(rChar)) {
                    match++;
                }
            }
            right++;

            while (match == needs.size()) {
                if (right - left == s1.length()) {
                    return true;
                }
                char lChar = s2.charAt(left);
                if (needs.containsKey(lChar)) {
                    int lCount = windows.get(lChar) - 1;
                    windows.put(lChar, lCount);
                    if (lCount < needs.get(lChar)) {
                        match--;
                    }
                }
                left++;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        _0567_PermutationInString solution = new _0567_PermutationInString();
        System.out.println(solution.checkInclusion("ab", "eidbaooo"));
        System.out.println(solution.checkInclusion("ab", "eidboaoo"));
    }
}

568. Maximum Vacation Days

1
Unresolved directive in 0568-maximum-vacation-days.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0568_MaximumVacationDays.java[]

569. Median Employee Salary

1
Unresolved directive in 0569-median-employee-salary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0569_MedianEmployeeSalary.java[]

570. Managers with at Least 5 Direct Reports

1
Unresolved directive in 0570-managers-with-at-least-5-direct-reports.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0570_ManagersWithAtLeast5DirectReports.java[]

571. Find Median Given Frequency of Numbers

1
Unresolved directive in 0571-find-median-given-frequency-of-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0571_FindMedianGivenFrequencyOfNumbers.java[]

572. Subtree of Another Tree

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

Example 1:

Given tree s:

     3
    / \
   4   5
  / \
 1   2

Given tree t:

   4
  / \
 1   2

Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

Given tree t:

   4
  / \
 1   2

Return false.

1
Unresolved directive in 0572-subtree-of-another-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0572_SubtreeOfAnotherTree.java[]

573. Squirrel Simulation

1
Unresolved directive in 0573-squirrel-simulation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0573_SquirrelSimulation.java[]

574. Winning Candidate

1
Unresolved directive in 0574-winning-candidate.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0574_WinningCandidate.java[]

575. Distribute Candies

Given an integer array with even length, where different numbers in this array represent different kinds of candies. Each number means one candy of the corresponding kind. You need to distribute these candies equally in number to brother and sister. Return the maximum number of kinds of candies the sister could gain.

Example 1:

Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
The sister has three different kinds of candies.

Example 2:

Input: candies = [1,1,2,3]
Output: 2
Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
The sister has two different kinds of candies, the brother has only one kind of candies.

Note:

  1. The length of the given array is in range [2, 10,000], and will be even.

  2. The number in given array is in range [-100,000, 100,000].

1
Unresolved directive in 0575-distribute-candies.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0575_DistributeCandies.java[]

576. Out of Boundary Paths

There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.

Example 1:

Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:

:https://assets.leetcode.com/uploads/2018/10/13/out_of_boundary_paths_1.png" alt="out of boundary paths 1">

Example 2:

Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/out_of_boundary_paths_2.png" alt="out of boundary paths 2">

Note:

  1. Once you move the ball out of boundary, you cannot move it back.

  2. The length and height of the grid is in range [1,50].

  3. N is in range [0,50].

1
Unresolved directive in 0576-out-of-boundary-paths.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0576_OutOfBoundaryPaths.java[]

577. Employee Bonus

1
Unresolved directive in 0577-employee-bonus.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0577_EmployeeBonus.java[]

578. Get Highest Answer Rate Question

1
Unresolved directive in 0578-get-highest-answer-rate-question.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0578_GetHighestAnswerRateQuestion.java[]

579. Find Cumulative Salary of an Employee

1
Unresolved directive in 0579-find-cumulative-salary-of-an-employee.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0579_FindCumulativeSalaryOfAnEmployee.java[]

580. Count Student Number in Departments

1
Unresolved directive in 0580-count-student-number-in-departments.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0580_CountStudentNumberInDepartments.java[]

581. Shortest Unsorted Continuous Subarray

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Note:

  1. Then length of the input array is in range [1, 10,000].

  2. The input array may contain duplicates, so ascending order here means .

解题分析

第一种办法就是对数组进行排序,然后跟原数组进行对比,看看那个元素变化了。

第二种办法就是从两边找逆序的小和大,然后再从两段寻找需要调整的元素。

思考题

再推敲一下从两段两段夹逼的阶梯方法。

参考资料

Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.

You need to find the shortest such subarray and output its length.

Example 1:

Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Note:

  1. Then length of the input array is in range [1, 10,000].

  2. The input array may contain duplicates, so ascending order here means .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.diguage.algorithm.leetcode;

/**
 * = 581. Shortest Unsorted Continuous Subarray
 *
 * https://leetcode.com/problems/shortest-unsorted-continuous-subarray/[Shortest Unsorted Continuous Subarray - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 21:44
 */
public class _0581_ShortestUnsortedContinuousSubarray {

    /**
     * Runtime: 4 ms, faster than 60.88% of Java online submissions for Shortest Unsorted Continuous Subarray.
     * Memory Usage: 51.8 MB, less than 7.69% of Java online submissions for Shortest Unsorted Continuous Subarray.
     */
    public int findUnsortedSubarray(int[] nums) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        boolean flag = false;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i - 1] > nums[i]) {
                flag = true;
            }
            if (flag) {
                min = Math.min(min, nums[i]);
            }
        }
        flag = false;
        for (int i = nums.length - 2; i >= 0; i--) {
            if (nums[i] > nums[i + 1]) {
                flag = true;
            }
            if (flag) {
                max = Math.max(max, nums[i]);
            }
        }
        int left, right;
        for (left = 0; left < nums.length; left++) {
            if (min < nums[left]) {
                break;
            }
        }
        for (right = nums.length - 1; right >= 0; right--) {
            if (max > nums[right]) {
                break;
            }
        }
        return right - left < 0 ? 0 : right - left + 1;
    }

    public static void main(String[] args) {
        _0581_ShortestUnsortedContinuousSubarray solution = new _0581_ShortestUnsortedContinuousSubarray();
        int[] n1 = {2, 6, 4, 8, 10, 9, 15};
        int r1 = solution.findUnsortedSubarray(n1);
        System.out.println((r1 == 5) + " : " + r1);
    }
}

582. Kill Process

1
Unresolved directive in 0582-kill-process.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0582_KillProcess.java[]

583. Delete Operation for Two Strings

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

  1. The length of given words won’t exceed 500.

  2. Characters in given words can only be lower-case letters.

1
Unresolved directive in 0583-delete-operation-for-two-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0583_DeleteOperationForTwoStrings.java[]

584. Find Customer Referee

1
Unresolved directive in 0584-find-customer-referee.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0584_FindCustomerReferee.java[]

585. Investments in 2016

1
Unresolved directive in 0585-investments-in-2016.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0585_InvestmentsIn2016.java[]

586. Customer Placing the Largest Number of Orders

1
Unresolved directive in 0586-customer-placing-the-largest-number-of-orders.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0586_CustomerPlacingTheLargestNumberOfOrders.java[]

587. Erect the Fence

There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden. Your job is to fence the entire garden using the minimum length of rope as it is expensive. The garden is well fenced only if all the trees are enclosed. Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.

Example 1:

Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]
Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/erect_the_fence_1.png" alt="erect the fence 1">

Example 2:

Input: [[1,2],[2,2],[4,2]]
Output: [[1,2],[2,2],[4,2]]
Explanation:

:https://assets.leetcode.com/uploads/2018/10/12/erect_the_fence_2.png" alt="erect the fence 2">
Even you only have trees in a line, you need to use rope to enclose them.

Note:

  1. All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them in more than one group.

  2. All input integers will range from 0 to 100.

  3. The garden has at least one tree.

  4. All coordinates are distinct.

  5. Input points have NO order. No order required for output.

  6. input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1
Unresolved directive in 0587-erect-the-fence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0587_ErectTheFence.java[]

588. Design In-Memory File System

1
Unresolved directive in 0588-design-in-memory-file-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0588_DesignInMemoryFileSystem.java[]

589. N-ary Tree Preorder Traversal

Given an n-ary tree, return the preorder traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Follow up:

Recursive solution is trivial, could you do it iteratively?

Example 1:

narytreeexample
Input: root = [1,null,3,2,4,null,5,6]
Output: [1,3,5,6,2,4]

Example 2:

sample 4 964
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]

Constraints:

  • The height of the n-ary tree is less than or equal to 1000

  • The total number of nodes is between [0, 10^4]

1
Unresolved directive in 0589-n-ary-tree-preorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0589_NAryTreePreorderTraversal.java[]

590. N-ary Tree Postorder Traversal

Given an n-ary tree, return the postorder traversal of its nodes' values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Follow up:

Recursive solution is trivial, could you do it iteratively?

Example 1:

narytreeexample
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]

Example 2:

sample 4 964
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]

Constraints:

  • The height of the n-ary tree is less than or equal to 1000

  • The total number of nodes is between [0, 10^4]

1
Unresolved directive in 0590-n-ary-tree-postorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0590_NAryTreePostorderTraversal.java[]

591. Tag Validator

Given a string representing a code snippet, you need to implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold:

  1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.

  2. A closed tag (not necessarily valid) has exactly the following format : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.

  3. A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.

  4. A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.

  5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.

  6. A < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).

  7. The cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.

  8. CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.

Valid Code Examples:

Input: "<DIV>This is the first line <![CDATA[<div>]]></DIV>"


Output: True


Explanation:
The code is wrapped in a closed tag : <DIV> and </DIV>.
The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata.
Although CDATA_CONTENT has unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as tag.
So TAG_CONTENT is valid, and then the code is valid. Thus return true.



Input: "<DIV>>>  ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"


Output: True


Explanation:


We first separate the code into : start_tag|tag_content|end_tag.


start_tag -> "<DIV>"


end_tag -> "</DIV>"


tag_content could also be separated into : text1|cdata|text2.


text1 -> ">>  ![cdata[]] "


cdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"


text2 -> "]]>>]"



The reason why start_tag is NOT "<DIV>>>" is because of the rule 6.
The reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.

Invalid Code Examples:

Input: "<A>  <B> </A>   </B>"
Output: False
Explanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.

Input: "<DIV>  div tag is not closed  <DIV>"
Output: False

Input: "<DIV>  unmatched &lt  </DIV>"
Output: False

Input: "<DIV> closed tags with invalid tag name  <b>123</b> </DIV>"
Output: False

Input: "<DIV> unmatched tags with invalid tag name  </1234567890> and <CDATA[[]]>  </DIV>"
Output: False

Input: "<DIV>  unmatched start tag <B>  and unmatched end tag </C>  </DIV>"
Output: False

Note:

  1. For simplicity, you could assume the input code (including the any characters mentioned above) only contain letters, digits, '<','>','/‘,’!‘,’[‘,’]' and ' '.

1
Unresolved directive in 0591-tag-validator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0591_TagValidator.java[]

592. Fraction Addition and Subtraction

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be <a href = "https://en.wikipedia.org/wiki/Irreducible_fraction">irreducible fraction</a>. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.

Example 1:

Input: "-1/2+1/2"
Output: "0/1"

Example 2:

Input: "-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input: "1/3-1/2"
Output: "-1/6"

Example 4:

Input: "5/3+1/3"
Output: "2/1"

Note:

  1. The input string only contains '0' to '9', '/', '+' and '-'. So does the output.

  2. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.

  3. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.

  4. The number of given fractions will be in the range [1,10].

  5. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

1
Unresolved directive in 0592-fraction-addition-and-subtraction.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0592_FractionAdditionAndSubtraction.java[]

593. Valid Square

Given the coordinates of four points in 2D space, return whether the four points could construct a square.

The coordinate (x,y) of a point is represented by an integer array with two integers.

Example:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True

Note:

  1. All the input integers are in the range [-10000, 10000].

  2. A valid square has four equal sides with positive length and four equal angles (90-degree angles).

  3. Input points have no order.

1
Unresolved directive in 0593-valid-square.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0593_ValidSquare.java[]

594. Longest Harmonious Subsequence

We define a harmounious array as an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible <a href="https://en.wikipedia.org/wiki/Subsequence">subsequences</a>.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

1
Unresolved directive in 0594-longest-harmonious-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0594_LongestHarmoniousSubsequence.java[]

595. Big Countries

There is a table World

----------------------------------------------------------------------
| name            | continent  | area       | population   | gdp           |
----------------------------------------------------------------------
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
----------------------------------------------------------------------

A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.

Write a SQL solution to output big countries' name, population and area.

For example, according to the above table, we should output:

-----------------------------------------
| name         | population  | area         |
-----------------------------------------
| Afghanistan  | 25500100    | 652230       |
| Algeria      | 37100000    | 2381741      |
-----------------------------------------
1
Unresolved directive in 0595-big-countries.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0595_BigCountries.java[]

596. Classes More Than 5 Students

There is a table courses with columns: student and class

Please list out all classes which have more than or equal to 5 students.

For example, the table:

---------------------+
| student | class      |
---------------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
---------------------+

Should output:

---------
| class   |
---------
| Math    |
---------

Note:

The students should not be counted duplicate in each course.

1
Unresolved directive in 0596-classes-more-than-5-students.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0596_ClassesMoreThan5Students.java[]

597. Friend Requests I: Overall Acceptance Rate

1
Unresolved directive in 0597-friend-requests-i-overall-acceptance-rate.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0597_FriendRequestsIOverallAcceptanceRate.java[]

598. Range Addition II

Given an m * n matrix M initialized with all 0's and several update operations. Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 ⇐ i < a and 0 ⇐ j < b. You need to count and return the number of maximum integers in the matrix after performing all the operations.

Example 1:

Input:
m = 3, n = 3
operations = [[2,2],[3,3]]
Output: 4
Explanation:
Initially, M =
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]

After performing [2,2], M =
[[1, 1, 0],
 [1, 1, 0],
 [0, 0, 0]]

After performing [3,3], M =
[[2, 2, 1],
 [2, 2, 1],
 [1, 1, 1]]

So the maximum integer in M is 2, and there are four of it in M. So return 4.

Note:

  1. The range of m and n is [1,40000].

  2. The range of a is [1,m], and the range of b is [1,n].

  3. The range of operations size won’t exceed 10,000.

1
Unresolved directive in 0598-range-addition-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0598_RangeAdditionII.java[]

599. Minimum Index Sum of Two Lists

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

Example 1:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".

Example 2:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).

Note:

  1. The length of both lists will be in the range of [1, 1000].

  2. The length of strings in both lists will be in the range of [1, 30].

  3. The index is starting from 0 to the list length minus 1.

  4. No duplicates in both lists.

1
Unresolved directive in 0599-minimum-index-sum-of-two-lists.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0599_MinimumIndexSumOfTwoLists.java[]

600. Non-negative Integers without Consecutive Ones

Given a positive integer n, find the number of non-negative integers less than or equal to n, whose binary representations do NOT contain consecutive ones.

Example 1:

Input: 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.

Note: 1 ⇐ n ⇐ 109

1
Unresolved directive in 0600-non-negative-integers-without-consecutive-ones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0600_NonNegativeIntegersWithoutConsecutiveOnes.java[]

601. Human Traffic of Stadium

X city built a new stadium, each day many people visit it and the stats are saved as these columns: id, visit_*date*, people

Please write a query to display the records which have 3 or more consecutive rows and the amount of people more than 100(inclusive). For example, the table stadium:

-----------------------------
| id   | visit_date | people    |
-----------------------------
| 1    | 2017-01-01 | 10        |
| 2    | 2017-01-02 | 109       |
| 3    | 2017-01-03 | 150       |
| 4    | 2017-01-04 | 99        |
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
-----------------------------

For the sample data above, the output is:

-----------------------------
| id   | visit_date | people    |
-----------------------------
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
-----------------------------

Note:

Each day only have one row record, and the dates are increasing with id increasing.

1
Unresolved directive in 0601-human-traffic-of-stadium.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0601_HumanTrafficOfStadium.java[]

602. Friend Requests II: Who Has the Most Friends

1
Unresolved directive in 0602-friend-requests-ii-who-has-the-most-friends.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0602_FriendRequestsIIWhoHasTheMostFriends.java[]

603. Consecutive Available Seats

1
Unresolved directive in 0603-consecutive-available-seats.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0603_ConsecutiveAvailableSeats.java[]

604. Design Compressed String Iterator

1
Unresolved directive in 0604-design-compressed-string-iterator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0604_DesignCompressedStringIterator.java[]

605. Can Place Flowers

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

Example 1:

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

Example 2:

Input: flowerbed = [1,0,0,0,1], n = 2
Output: False

Note:

  1. The input array won’t violate no-adjacent-flowers rule.

  2. The input array size is in the range of [1, 20000].

  3. n is a non-negative integer which won’t exceed the input array size.

1
Unresolved directive in 0605-can-place-flowers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0605_CanPlaceFlowers.java[]

606. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /
  4

Output: "1(2(4))(3)"
<br/>*Explanation:* Originallay it needs to be "1(2(4)())(3()())", <br/>but you need to omit all the unnecessary empty parenthesis pairs. <br/>And it will be "1(2(4))(3)".

Example 2:

Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \
      4

Output: "1(2()(4))(3)"
<br/>*Explanation:* Almost the same as the first example, <br/>except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
1
Unresolved directive in 0606-construct-string-from-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0606_ConstructStringFromBinaryTree.java[]

607. Sales Person

1
Unresolved directive in 0607-sales-person.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0607_SalesPerson.java[]

608. Tree Node

1
Unresolved directive in 0608-tree-node.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0608_TreeNode.java[]

609. Find Duplicate File in System

Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.

A group of duplicate files consists of at least two files that have exactly the same content.

A single directory info string in the input list has the following format:

"root/d1/d2/…​/dm f1.txt(f1_content) f2.txt(f2_content) …​ fn.txt(fn_content)"

It means there are n files (f1.txt, f2.txt …​ fn.txt with content f1_content, f2_content …​ fn_content, respectively) in directory root/d1/d2/…​/dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

"directory_path/file_name.txt"

Example 1:

Input:
["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]
Output:
[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]

Note:

  1. No order is required for the final output.

  2. You may assume the directory name, file name and file content only has letters and digits, and the length of file content is in the range of [1,50].

  3. The number of files given is in the range of [1,20000].

  4. You may assume no files or directories share the same name in the same directory.

  5. You may assume each given directory info represents a unique directory. Directory path and file info are separated by a single blank space.

Follow-up beyond contest:

  1. Imagine you are given a real file system, how will you search files? DFS or BFS?

  2. If the file content is very large (GB level), how will you modify your solution?

  3. If you can only read the file by 1kb each time, how will you modify your solution?

  4. What is the time complexity of your modified solution? What is the most time-consuming part and memory consuming part of it? How to optimize?

  5. How to make sure the duplicated files you find are not false positive?

1
Unresolved directive in 0609-find-duplicate-file-in-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0609_FindDuplicateFileInSystem.java[]

610. Triangle Judgement

1
Unresolved directive in 0610-triangle-judgement.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0610_TriangleJudgement.java[]

611. Valid Triangle Number

Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

Example 1:

Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

Note:

  1. The length of the given array won’t exceed 1000.

  2. The integers in the given array are in the range of [0, 1000].

1
Unresolved directive in 0611-valid-triangle-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0611_ValidTriangleNumber.java[]

612. Shortest Distance in a Plane

1
Unresolved directive in 0612-shortest-distance-in-a-plane.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0612_ShortestDistanceInAPlane.java[]

613. Shortest Distance in a Line

1
Unresolved directive in 0613-shortest-distance-in-a-line.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0613_ShortestDistanceInALine.java[]

614. Second Degree Follower

1
Unresolved directive in 0614-second-degree-follower.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0614_SecondDegreeFollower.java[]

615. Average Salary: Departments VS Company

1
Unresolved directive in 0615-average-salary-departments-vs-company.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0615_AverageSalaryDepartmentsVSCompany.java[]

616. Add Bold Tag in String

1
Unresolved directive in 0616-add-bold-tag-in-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0616_AddBoldTagInString.java[]

617. Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example:
Input:
      Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7
Output:
      Merged tree:
          3
         / \
        4   5
       / \   \
      5   4   7

Note: The merging process must start from the root nodes of both trees.

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input:
	Tree 1                     Tree 2
          1                         2
         / \                       / \
        3   2                     1   3
       /                           \   \
      5                             4   7
Output:
Merged tree:
	     3
	    / \
	   4   5
	  / \   \
	 5   4   7

Note: The merging process must start from the root nodes of both trees.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.diguage.algorithm.leetcode;

import com.diguage.algorithm.util.JsonUtils;
import com.diguage.algorithm.util.TreeNode;

import java.util.Objects;

import static com.diguage.algorithm.util.TreeNodeUtils.buildTree;
import static java.util.Arrays.asList;

/**
 * = 617. Merge Two Binary Trees
 *
 * https://leetcode.com/problems/merge-two-binary-trees/[Merge Two Binary Trees - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-29 16:17
 */
public class _0617_MergeTwoBinaryTrees {

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Merge Two Binary Trees.
     * Memory Usage: 41.6 MB, less than 22.22% of Java online submissions for Merge Two Binary Trees.
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (Objects.isNull(t1)) {
            return t2;
        }
        if (Objects.isNull(t2)) {
            return t1;
        }
        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        return t1;
    }

    public static void main(String[] args) {
        _0617_MergeTwoBinaryTrees solution = new _0617_MergeTwoBinaryTrees();
        TreeNode r1 = solution.mergeTrees(buildTree(asList(1, 3, 2, 5)), buildTree(asList(2, 1, 3, null, 4, 7)));
        System.out.println(JsonUtils.toJson(r1));
    }
}

618. Students Report By Geography

1
Unresolved directive in 0618-students-report-by-geography.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0618_StudentsReportByGeography.java[]

619. Biggest Single Number

1
Unresolved directive in 0619-biggest-single-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0619_BiggestSingleNumber.java[]

620. Not Boring Movies

X city opened a new cinema, many people would like to go to this cinema. The cinema also gives out a poster indicating the movies’ ratings and descriptions. Please write a SQL query to output movies with an odd numbered ID and a description that is not 'boring'. Order the result by rating.

For example, table cinema:

---------------------------------------------+
|   id    | movie     |  description |  rating   |
---------------------------------------------+
|   1     | War       |   great 3D   |   8.9     |
|   2     | Science   |   fiction    |   8.5     |
|   3     | irish     |   boring     |   6.2     |
|   4     | Ice song  |   Fantacy    |   8.6     |
|   5     | House card|   Interesting|   9.1     |
---------------------------------------------+

For the example above, the output should be:

---------------------------------------------+
|   id    | movie     |  description |  rating   |
---------------------------------------------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
---------------------------------------------+
1
Unresolved directive in 0620-not-boring-movies.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0620_NotBoringMovies.java[]

621. Task Scheduler

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Note:

  1. The number of tasks is in the range [1, 10000].

  2. The integer n is in the range [0, 100].

解题分析

这道题有三个点需要注意:

  1. 因为要任务休息时间,所以,出现次数最多的任务,会持续得更长,有将任务按照出现次数排序,优先安排次数多的任务。

  2. 结果关注的是总共需要完成的时间,所以不需要关注具体执行的是哪个任务。

  3. 需要"空转时间"的处理。

解题思路:

  1. 将任务按类型分组,正好A-Z用一个int[26]保存任务类型个数

  2. 对数组进行排序,优先排列个数(count)最大的任务,如题得到的时间至少为 retCount =(count-1)* (n+1) + 1 =⇒ A→X→X→A→X→X→A(X为其他任务或者待命)

  3. 再排序下一个任务,如果下一个任务B个数和最大任务数一致,则retCount++ =⇒ A→B→X→A→B→X→A→B

  4. 如果空位都插满之后还有任务,那就随便在这些间隔里面插入就可以,因为间隔长度肯定会大于n,在这种情况下就是任务的总数是最小所需时间

参考资料

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Note:

  1. The number of tasks is in the range [1, 10000].

  2. The integer n is in the range [0, 100].

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
package com.diguage.algorithm.leetcode;

import java.util.*;

/**
 * = 621. Task Scheduler
 *
 * https://leetcode.com/problems/task-scheduler/[Task Scheduler - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-31 21:26
 */
public class _0621_TaskScheduler {
    /**
     * Runtime: 2 ms, faster than 99.97% of Java online submissions for Task Scheduler.
     * Memory Usage: 42.7 MB, less than 5.88% of Java online submissions for Task Scheduler.
     *
     * Copy from: https://leetcode-cn.com/problems/task-scheduler/solution/621-ren-wu-diao-du-qi-java-jie-ti-zhu-shi-ying-gai/[621. 任务调度器--Java--解题注释应该能看懂 - 任务调度器 - 力扣(LeetCode)]
     */
    public int leastInterval(char[] tasks, int n) {
        if (Objects.isNull(tasks) || tasks.length == 0) {
            return 0;
        }
        int[] counts = new int[26];
        for (char task : tasks) {
            counts[task - 'A']++;
        }
        Arrays.sort(counts);
        int maxCount = counts[25];
        int restCount = (maxCount - 1) * (n + 1) + 1;
        for (int i = 24; i >= 0 && counts[i] == maxCount; i--) {
            restCount++;
        }
        return Math.max(restCount, tasks.length);
    }

    /**
     * Runtime: 2 ms, faster than 99.97% of Java online submissions for Task Scheduler.
     * Memory Usage: 42.6 MB, less than 5.88% of Java online submissions for Task Scheduler.
     * <p>
     * Copy from: https://leetcode-cn.com/problems/task-scheduler/solution/ren-wu-diao-du-qi-by-leetcode/[任务调度器 - 任务调度器 - 力扣(LeetCode)]
     */
    public int leastInterval1(char[] tasks, int n) {
        if (Objects.isNull(tasks) || tasks.length == 0) {
            return 0;
        }
        int[] counts = new int[26];
        for (char task : tasks) {
            counts[task - 'A']++;
        }
        Arrays.sort(counts);
        int maxValue = counts[25] - 1;
        int idleSlots = maxValue * n;
        for (int i = 24; i >= 0 && counts[i] > 0; i--) {
            idleSlots -= Math.min(maxValue, counts[i]);
        }
        return idleSlots > 0 ? idleSlots + tasks.length : tasks.length;
    }

    /**
     * Runtime: 29 ms, faster than 42.49% of Java online submissions for Task Scheduler.
     * Memory Usage: 41.9 MB, less than 5.88% of Java online submissions for Task Scheduler.
     * <p>
     * Copy from: https://leetcode-cn.com/problems/task-scheduler/solution/ren-wu-diao-du-qi-by-leetcode/[任务调度器 - 任务调度器 - 力扣(LeetCode)]
     */
    public int leastIntervalQueue(char[] tasks, int n) {
        if (Objects.isNull(tasks) || tasks.length == 0) {
            return 0;
        }
        int[] counts = new int[26];
        for (char c : tasks) {
            counts[c - 'A']++;
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
        for (int count : counts) {
            if (count > 0) {
                queue.add(count);
            }
        }
        int time = 0;
        while (!queue.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            int i = 0;
            while (i <= n) {
                if (!queue.isEmpty()) {
                    if (queue.peek() > 1) {
                        temp.add(queue.poll() - 1);
                    } else {
                        queue.poll();
                    }
                }
                time++;
                i++;
                if (queue.isEmpty() && temp.isEmpty()) {
                    break;
                }
            }
            for (Integer count : temp) {
                queue.add(count);
            }
        }
        return time;
    }

    public static void main(String[] args) {
        _0621_TaskScheduler solution = new _0621_TaskScheduler();
        int r1 = solution.leastInterval("AAABBB".toCharArray(), 2);
        System.out.println((r1 == 8) + " : " + r1);
    }
}

622. Design Circular Queue

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

Your implementation should support following operations:

  • MyCircularQueue(k): Constructor, set the size of the queue to be k.

  • Front: Get the front item from the queue. If the queue is empty, return -1.

  • Rear: Get the last item from the queue. If the queue is empty, return -1.

  • enQueue(value): Insert an element into the circular queue. Return true if the operation is successful.

  • deQueue(): Delete an element from the circular queue. Return true if the operation is successful.

  • isEmpty(): Checks whether the circular queue is empty or not.

  • isFull(): Checks whether the circular queue is full or not.

Example:

MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
circularQueue.enQueue(1);  // return true
circularQueue.enQueue(2);  // return true
circularQueue.enQueue(3);  // return true
circularQueue.enQueue(4);  // return false, the queue is full
circularQueue.Rear();  // return 3
circularQueue.isFull();  // return true
circularQueue.deQueue();  // return true
circularQueue.enQueue(4);  // return true
circularQueue.Rear();  // return 4

Note:

  • All values will be in the range of [0, 1000].

  • The number of operations will be in the range of [1, 1000].

  • Please do not use the built-in Queue library.

1
Unresolved directive in 0622-design-circular-queue.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0622_DesignCircularQueue.java[]

623. Add One Row to Tree

Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1.

The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N’s left subtree root and right subtree root. And N’s original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root’s left subtree.

Example 1:

Input:
A binary tree as following:
       4
     /   \
    2     6
   / \   /
  3   1 5

v = 1

d = 2

Output:
       4
      / \
     1   1
    /     \
   2       6
  / \     /
 3   1   5

Example 2:

Input:
A binary tree as following:
      4
     /
    2
   / \
  3   1

v = 1

d = 3

Output:
      4
     /
    2
   / \
  1   1
 /     \
3       1

Note:

  1. The given d is in range [1, maximum depth of the given tree + 1].

  2. The given binary tree has at least one tree node.

1
Unresolved directive in 0623-add-one-row-to-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0623_AddOneRowToTree.java[]

624. Maximum Distance in Arrays

1
Unresolved directive in 0624-maximum-distance-in-arrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0624_MaximumDistanceInArrays.java[]

625. Minimum Factorization

1
Unresolved directive in 0625-minimum-factorization.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0625_MinimumFactorization.java[]

626. Exchange Seats

Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids. The column id is continuous increment.

Mary wants to change seats for the adjacent students.

Can you write a SQL query to output the result for Mary?

------------------+
|    id   | student |
------------------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
------------------+

For the sample input, the output is:

------------------+
|    id   | student |
------------------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
------------------+

Note:

If the number of students is odd, there is no need to change the last one’s seat.

1
Unresolved directive in 0626-exchange-seats.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0626_ExchangeSeats.java[]

627. Swap Salary

Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement and no intermediate temp table.

Note that you must write a single update statement, DO NOT write any select statement for this problem.

Example:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |

After running your update statement, the above salary table should have the following rows:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
1
Unresolved directive in 0627-swap-salary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0627_SwapSalary.java[]

628. Maximum Product of Three Numbers

Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:

Input: [1,2,3]
Output: 6

Example 2:

Input: [1,2,3,4]
Output: 24

Note:

  1. The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].

  2. Multiplication of any three numbers in the input won’t exceed the range of 32-bit signed integer.

1
Unresolved directive in 0628-maximum-product-of-three-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0628_MaximumProductOfThreeNumbers.java[]

629. K Inverse Pairs Array

Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs.

We define an inverse pair as following: For ith and jth element in the array, if i < j and a[i] > a[j] then it’s an inverse pair; Otherwise, it’s not.

Since the answer may be very large, the answer should be modulo 109 + 7.

Example 1:

Input: n = 3, k = 0
Output: 1
Explanation:
Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.

Example 2:

Input: n = 3, k = 1
Output: 2
Explanation:
The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.

Note:

  1. The integer n is in the range [1, 1000] and k is in the range [0, 1000].

1
Unresolved directive in 0629-k-inverse-pairs-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0629_KInversePairsArray.java[]

630. Course Schedule III

There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

Example:

Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Output: 3
Explanation:
There're totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day.
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day.
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.

Note:

  1. The integer 1 ⇐ d, t, n ⇐ 10,000.

  2. You can’t take two courses simultaneously.

1
Unresolved directive in 0630-course-schedule-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0630_CourseScheduleIII.java[]

631. Design Excel Sum Formula

1
Unresolved directive in 0631-design-excel-sum-formula.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0631_DesignExcelSumFormula.java[]

632. Smallest Range Covering Elements from K Lists

You have k lists of sorted integers in ascending order. Find the smallest range that includes at least one number from each of the k lists.

We define the range [a,b] is smaller than range [c,d] if b-a < d-c or a < c if b-a == d-c.

Example 1:

Input: [[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].

Note:

  1. The given list may contain duplicates, so ascending order means >= here.

  2. 1 ⇐ k ⇐ 3500

  3. -105value of elements ⇐ 105.

1
Unresolved directive in 0632-smallest-range-covering-elements-from-k-lists.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0632_SmallestRangeCoveringElementsFromKLists.java[]

633. Sum of Square Numbers

Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.

Example 1:

Input: 5
Output: True
Explanation: 1  1 + 2  2 = 5

Example 2:

Input: 3
Output: False
1
Unresolved directive in 0633-sum-of-square-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0633_SumOfSquareNumbers.java[]

634. Find the Derangement of An Array

1
Unresolved directive in 0634-find-the-derangement-of-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0634_FindTheDerangementOfAnArray.java[]

635. Design Log Storage System

1
Unresolved directive in 0635-design-log-storage-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0635_DesignLogStorageSystem.java[]

636. Exclusive Time of Functions

On a single threaded CPU, we execute some functions. Each function has a unique id between 0 and N-1.

We store logs in timestamp order that describe when a function is entered or exited.

Each log is a string with this format: "{function_id}:{"start" | "end"}:{timestamp}". For example, "0:start:3" means the function with id 0 started at the beginning of timestamp 3. "1:end:2" means the function with id 1 ended at the end of timestamp 2.

A function’s exclusive time is the number of units of time spent in this function. Note that this does not include any recursive calls to child functions.

The CPU is single threaded which means that only one function is being executed at a given time unit.

Return the exclusive time of each function, sorted by their function id.

Example 1:

image::https://assets.leetcode.com/uploads/2019/04/05/diag1b.png[]

Input:
n = 2
logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]
Output: [3, 4]
Explanation:
Function 0 starts at the beginning of time 0, then it executes 2 units of time and reaches the end of time 1.
Now function 1 starts at the beginning of time 2, executes 4 units of time and ends at time 5.
Function 0 is running again at the beginning of time 6, and also ends at the end of time 6, thus executing for 1 unit of time.
So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.

Note:

  1. 1 ⇐ n ⇐ 100

  2. Two functions won’t start or end at the same time.

  3. Functions will always log when they exit.

1
Unresolved directive in 0636-exclusive-time-of-functions.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0636_ExclusiveTimeOfFunctions.java[]

637. Average of Levels in Binary Tree

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example 1:

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

Note:

  1. The range of node’s value is in the range of 32-bit signed integer.

1
Unresolved directive in 0637-average-of-levels-in-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0637_AverageOfLevelsInBinaryTree.java[]

638. Shopping Offers

In LeetCode Store, there are some kinds of items to sell. Each item has a price.

However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given the each item’s price, a set of special offers, and the number we need to buy for each item. The job is to output the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers.

Each special offer is represented in the form of an array, the last number represents the price you need to pay for this special offer, other numbers represents how many specific items you could get if you buy this offer.

You could use any of special offers as many times as you want.

Example 1:

Input: [2,5], [[3,0,5],[1,2,10]], [3,2]
Output: 14
Explanation:
There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

Example 2:

Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
Output: 11
Explanation:
The price of A is $2, and $3 for B, $4 for C.
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
You cannot add more items, though only $9 for 2A ,2B and 1C.

Note:

  1. There are at most 6 kinds of items, 100 special offers.

  2. For each item, you need to buy at most 6 of them.

  3. You are not allowed to buy more items than you want, even if that would lower the overall price.

1
Unresolved directive in 0638-shopping-offers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0638_ShoppingOffers.java[]

639. Decode Ways II

A message containing letters from A-Z is being encoded to numbers using the following mapping way:

'A' -> 1
'B' -> 2
...
'Z' -> 26

Beyond that, now the encoded string can also contain the character '*', which can be treated as one of the numbers from 1 to 9.

Given the encoded message containing digits and the character '*', return the total number of ways to decode it.

Also, since the answer may be very large, you should return the output mod 109 + 7.

Example 1:

Input: ""
Output: 9
Explanation:* The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".

Example 2:

Input: "1*"
Output: 9 + 9 = 18

Note:

  1. The length of the input string will fit in range [1, 105].

  2. The input string will only contain the character '*' and digits '0' - '9'.

1
Unresolved directive in 0639-decode-ways-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0639_DecodeWaysII.java[]

640. Solve the Equation

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.

If there is no solution for the equation, return "No solution".

If there are infinite solutions for the equation, return "Infinite solutions".

If there is exactly one solution for the equation, we ensure that the value of x is an integer.

Example 1:<br/>

Input: "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:<br/>

Input: "x=x"
Output: "Infinite solutions"

Example 3:<br/>

Input: "2x=x"
Output: "x=0"

Example 4:<br/>

Input: "2x+3x-6x=x+2"
Output: "x=-1"

Example 5:<br/>

Input: "x=x+2"
Output: "No solution"
1
Unresolved directive in 0640-solve-the-equation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0640_SolveTheEquation.java[]

641. Design Circular Deque

Design your implementation of the circular double-ended queue (deque).

Your implementation should support following operations:

  • MyCircularDeque(k): Constructor, set the size of the deque to be k.

  • insertFront(): Adds an item at the front of Deque. Return true if the operation is successful.

  • insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.

  • deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.

  • deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.

  • getFront(): Gets the front item from the Deque. If the deque is empty, return -1.

  • getRear(): Gets the last item from Deque. If the deque is empty, return -1.

  • isEmpty(): Checks whether Deque is empty or not.

  • isFull(): Checks whether Deque is full or not.

Example:

MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3
circularDeque.insertLast(1);			// return true
circularDeque.insertLast(2);			// return true
circularDeque.insertFront(3);			// return true
circularDeque.insertFront(4);			// return false, the queue is full
circularDeque.getRear();  			// return 2
circularDeque.isFull();				// return true
circularDeque.deleteLast();			// return true
circularDeque.insertFront(4);			// return true
circularDeque.getFront();			// return 4

Note:

  • All values will be in the range of [0, 1000].

  • The number of operations will be in the range of [1, 1000].

  • Please do not use the built-in Deque library.

1
Unresolved directive in 0641-design-circular-deque.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0641_DesignCircularDeque.java[]

642. Design Search Autocomplete System

1
Unresolved directive in 0642-design-search-autocomplete-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0642_DesignSearchAutocompleteSystem.java[]

643. Maximum Average Subarray I

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

  1. 1 ⇐ kn ⇐ 30,000.

  2. Elements of the given array will be in the range [-10,000, 10,000].

1
Unresolved directive in 0643-maximum-average-subarray-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0643_MaximumAverageSubarrayI.java[]

644. Maximum Average Subarray II

1
Unresolved directive in 0644-maximum-average-subarray-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0644_MaximumAverageSubarrayII.java[]

645. Set Mismatch

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Note:

  1. The given array size will in the range [2, 10000].

  2. The given array’s numbers won’t have any order.

1
Unresolved directive in 0645-set-mismatch.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0645_SetMismatch.java[]

646. Maximum Length of Pair Chain

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.

Given a set of pairs, find the length longest chain which can be formed. You needn’t use up all the given pairs. You can select pairs in any order.

Example 1:

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

Note:

  1. The number of given pairs will be in the range [1, 1000].

1
Unresolved directive in 0646-maximum-length-of-pair-chain.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0646_MaximumLengthOfPairChain.java[]

647. Palindromic Substrings

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won’t exceed 1000.

解题思路

马拉车算法

思考题

学习马拉车算法。

参考资料

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won’t exceed 1000.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.diguage.algorithm.leetcode;

/**
 * = 647. Palindromic Substrings
 *
 * https://leetcode.com/problems/palindromic-substrings/[Palindromic Substrings - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-31 23:17
 */
public class _0647_PalindromicSubstrings {
    /**
     * Runtime: 1 ms, faster than 100.00% of Java online submissions for Palindromic Substrings.
     * Memory Usage: 37.8 MB, less than 11.39% of Java online submissions for Palindromic Substrings.
     *
     * Copy from: https://leetcode-cn.com/problems/palindromic-substrings/solution/hui-wen-zi-chuan-by-leetcode/[回文子串 - 回文子串 - 力扣(LeetCode)]
     */
    public int countSubstrings(String s) {
        char[] A = new char[2 * s.length() + 3];
        A[0] = '@';
        A[1] = '#';
        A[A.length - 1] = '$';
        int j = 2;
        for (char c : s.toCharArray()) {
            A[j++] = c;
            A[j++] = '#';
        }

        int[] Z = new int[A.length];
        int center = 0, right = 0;
        for (int i = 1; i < Z.length - 1; i++) {
            if (i < right) {
                Z[i] = Math.min(right - i, Z[2 * center - i]);
            }
            while (A[i + Z[i] + 1] == A[i - Z[i] - 1]) {
                Z[i]++;
            }
            if (i + Z[i] > right) {
                center = i;
                right = i + Z[i];
            }
        }
        int result = 0;
        for (int i : Z) {
            result += (i + 1) / 2;
        }
        return result;
    }

    public static void main(String[] args) {
        _0647_PalindromicSubstrings solution = new _0647_PalindromicSubstrings();
        int r1 = solution.countSubstrings("abc");
        System.out.println((r1 == 3) + " : " + r1);

        int r2 = solution.countSubstrings("aaa");
        System.out.println((r2 == 6) + " : " + r2);
    }
}

648. Replace Words

In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"

Note:

  1. The input will only have lower-case letters.

  2. 1 ⇐ dict words number ⇐ 1000

  3. 1 ⇐ sentence words number ⇐ 1000

  4. 1 ⇐ root length ⇐ 100

  5. 1 ⇐ sentence words length ⇐ 1000

1
Unresolved directive in 0648-replace-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0648_ReplaceWords.java[]

649. Dota2 Senate

In the world of Dota2, there are two parties: the Radiant and the Dire.

The Dota2 senate consists of senators coming from two parties. Now the senate wants to make a decision about a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:

  1. Ban one senator’s right:

    	A senator can make another senator lose *all his rights* in this and all the following rounds.
    . `Announce the victory`:
    If this senator found the senators who still have rights to vote are all from *the same party*, he can announce the victory and make the decision about the change in the game.

Given a string representing each senator’s party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party respectively. Then if there are n senators, the size of the given string will be n.

The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.

Suppose every senator is smart enough and will play the best strategy for his own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.

Example 1:

Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next senator's right in the round 1.
And the second senator can't exercise any rights any more since his right has been banned.
And in the round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.

Example 2:

Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in the round 1.
And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.

Note:

  1. The length of the given string will in the range [1, 10,000].

1
Unresolved directive in 0649-dota2-senate.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0649_Dota2Senate.java[]

650. 2 Keys Keyboard

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).

  2. Paste: You can paste the characters which are copied last time.

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:

  1. The n will be in the range [1, 1000].

1
Unresolved directive in 0650-2-keys-keyboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0650_2KeysKeyboard.java[]

651. 4 Keys Keyboard

1
Unresolved directive in 0651-4-keys-keyboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0651_4KeysKeyboard.java[]

652. Find Duplicate Subtrees

Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with same node values.

*Example 1: *

        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4

The following are two duplicate subtrees:

      2
     /
    4

and

    4

Therefore, you need to return above trees' root in the form of a list.

1
Unresolved directive in 0652-find-duplicate-subtrees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0652_FindDuplicateSubtrees.java[]

653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input:
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

Example 2:

Input:
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False
1
Unresolved directive in 0653-two-sum-iv-input-is-a-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0653_TwoSumIVInputIsABST.java[]

654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.

  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.

  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    /
     2  0
       \
        1

Note:

  1. The size of the given array will be in the range [1,1000].

1
Unresolved directive in 0654-maximum-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0654_MaximumBinaryTree.java[]

655. Print Binary Tree

Print a binary tree in an m*n 2D string array following these rules:

  1. The row number m should be equal to the height of the given binary tree.

  2. The column number n should always be an odd number.

  3. The root node’s value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don’t need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don’t need to leave space for both of them.

  4. Each unused space should contain an empty string "".

  5. Print the subtrees following the same rules.

Example 1:

Input:
     1
    /
   2
Output:
[["", "1", ""],
 ["2", "", ""]]

Example 2:

Input:
     1
    / \
   2   3
    \
     4
Output:
[["", "", "", "1", "", "", ""],
 ["", "2", "", "", "", "3", ""],
 ["", "", "4", "", "", "", ""]]

Example 3:

Input:
      1
     / \
    2   5
   /
  3
 /
4
Output:

[["",  "",  "", "",  "", "", "", "1", "",  "",  "",  "",  "", "", ""]
 ["",  "",  "", "2", "", "", "", "",  "",  "",  "",  "5", "", "", ""]
 ["",  "3", "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]
 ["4", "",  "", "",  "", "", "", "",  "",  "",  "",  "",  "", "", ""]]

Note: The height of binary tree is in the range of [1, 10].

1
Unresolved directive in 0655-print-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0655_PrintBinaryTree.java[]

656. Coin Path

1
Unresolved directive in 0656-coin-path.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0656_CoinPath.java[]

657. Robot Return to Origin

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot’s movement is the same for each move.

Example 1:

Input: "UD"
Output: true
Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.

Example 2:

Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
1
Unresolved directive in 0657-robot-return-to-origin.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0657_RobotReturnToOrigin.java[]

658. Find K Closest Elements

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:

Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]

Example 2:

Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]

Note:

  1. The value k is positive and will always be smaller than the length of the sorted array.

  2. Length of the given array is positive and will not exceed 104

  3. Absolute value of elements in the array and x will not exceed 104

<hr />

<font color="red">UPDATE (2017/9/19):

The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.

1
Unresolved directive in 0658-find-k-closest-elements.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0658_FindKClosestElements.java[]

659. Split Array into Consecutive Subsequences

Given an array nums sorted in ascending order, return true if and only if you can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3.

Example 1:

Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3
3, 4, 5

Example 2:

Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3, 4, 5
3, 4, 5

Example 3:

Input: [1,2,3,4,4,5]
Output: False

Constraints:

  • 1 ⇐ nums.length ⇐ 10000

1
Unresolved directive in 0659-split-array-into-consecutive-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0659_SplitArrayIntoConsecutiveSubsequences.java[]

660. Remove 9

1
Unresolved directive in 0660-remove-9.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0660_Remove9.java[]

661. Image Smoother

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

Example 1:

Input:
[[1,1,1],
 [1,0,1],
 [1,1,1]]
Output:
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]
Explanation:
For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

Note:

  1. The value in the given matrix is in the range of [0, 255].

  2. The length and width of the given matrix are in the range of [1, 150].

1
Unresolved directive in 0661-image-smoother.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0661_ImageSmoother.java[]

662. Maximum Width of Binary Tree

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

Example 1:

Input:

           1
         /   \
        3     2
       / \     \
      5   3     9

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input:

          1
         /
        3
       / \
      5   3

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input:

          1
         / \
        3   2
       /
      5

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input:

          1
         / \
        3   2
       /     \
      5       9
     /         \
    6           7
Output: 8
Explanation: The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

Note: Answer will in the range of 32-bit signed integer.

1
Unresolved directive in 0662-maximum-width-of-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0662_MaximumWidthOfBinaryTree.java[]

663. Equal Tree Partition

1
Unresolved directive in 0663-equal-tree-partition.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0663_EqualTreePartition.java[]

664. Strange Printer

There is a strange printer with the following two special requirements:

  1. The printer can only print a sequence of the same character each time.

  2. At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.

Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.

Example 1:

Input: "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".

Example 2:

Input: "aba"
Output: 2
Explanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.

Hint: Length of the given string will not exceed 100.

1
Unresolved directive in 0664-strange-printer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0664_StrangePrinter.java[]

665. Non-decreasing Array

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] ⇐ array[i + 1] holds for every i (1 ⇐ i < n).

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note: The n belongs to [1, 10,000].

1
Unresolved directive in 0665-non-decreasing-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0665_NonDecreasingArray.java[]

666. Path Sum IV

1
Unresolved directive in 0666-path-sum-iv.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0666_PathSumIV.java[]

667. Beautiful Arrangement II

Given two integers n and k, you need to construct a list which contains n different positive integers ranging from 1 to n and obeys the following requirement: <br/>

Suppose this list is [a1, a2, a3, …​ , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, …​ , |an-1 - an|] has exactly k distinct integers.

If there are multiple answers, print any of them.

Example 1:<br/>

Input: n = 3, k = 1
Output: [1, 2, 3]
Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.

Example 2:

Input: n = 3, k = 2
Output: [1, 3, 2]
Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.

Note:

  1. The n and k are in the range 1 ⇐ k < n ⇐ 104.

1
Unresolved directive in 0667-beautiful-arrangement-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0667_BeautifulArrangementII.java[]

668. Kth Smallest Number in Multiplication Table

Nearly every one have used the <a href="https://en.wikipedia.org/wiki/Multiplication_table">Multiplication Table</a>. But could you find out the k-th smallest number quickly from the multiplication table?

Given the height m and the length n of a m * n Multiplication Table, and a positive integer k, you need to return the k-th smallest number in this table.

Example 1:

Input: m = 3, n = 3, k = 5
Output:
Explanation:
The Multiplication Table:
1	2	3
2	4	6
3	6	9

The 5-th smallest number is 3 (1, 2, 2, 3, 3).

Example 2:

Input: m = 2, n = 3, k = 6
Output:
Explanation:
The Multiplication Table:
1	2	3
2	4	6

The 6-th smallest number is 6 (1, 2, 2, 3, 4, 6).

Note:

  1. The m and n will be in the range [1, 30000].

  2. The k will be in the range [1, m * n]

1
Unresolved directive in 0668-kth-smallest-number-in-multiplication-table.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0668_KthSmallestNumberInMultiplicationTable.java[]

669. Trim a Binary Search Tree

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.

Example 1:

Input:
    1
   / \
  0   2

  L = 1
  R = 2

Output:
    1
      \
       2

Example 2:

Input:
    3
   / \
  0   4
   \
    2
   /
  1

  L = 1
  R = 3

Output:
      3
     /
   2
  /
 1
1
Unresolved directive in 0669-trim-a-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0669_TrimABinarySearchTree.java[]

670. Maximum Swap

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

  1. The given number is in the range [0, 108]

1
Unresolved directive in 0670-maximum-swap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0670_MaximumSwap.java[]

671. Second Minimum Node In a Binary Tree

Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example 1:

Input:
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input:
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
1
Unresolved directive in 0671-second-minimum-node-in-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0671_SecondMinimumNodeInABinaryTree.java[]

672. Bulb Switcher II

There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly m unknown operations towards buttons, you need to return how many different kinds of status of the n lights could be.

Suppose n lights are labeled as number [1, 2, 3 …​, n], function of these 4 buttons are given below:

  1. Flip all the lights.

  2. Flip lights with even numbers.

  3. Flip lights with odd numbers.

  4. Flip lights with (3k + 1) numbers, k = 0, 1, 2, …​

Example 1:

Input: n = 1, m = 1.
Output: 2
Explanation: Status can be: [on], [off]

Example 2:

Input: n = 2, m = 1.
Output: 3
Explanation: Status can be: [on, off], [off, on], [off, off]

Example 3:

Input: n = 3, m = 1.
Output: 4
Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].

Note: n and m both fit in range [0, 1000].

1
Unresolved directive in 0672-bulb-switcher-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0672_BulbSwitcherII.java[]

673. Number of Longest Increasing Subsequence

Given an unsorted array of integers, find the number of longest increasing subsequence.

Example 1:

Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.

Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.

1
Unresolved directive in 0673-number-of-longest-increasing-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0673_NumberOfLongestIncreasingSubsequence.java[]

674. Longest Continuous Increasing Subsequence

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:

Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.

Example 2:

Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.

Note: Length of the array will not exceed 10,000.

1
Unresolved directive in 0674-longest-continuous-increasing-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0674_LongestContinuousIncreasingSubsequence.java[]

675. Cut Off Trees for Golf Event

You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, in this map:

  1. 0 represents the obstacle can’t be reached.

  2. 1 represents the ground can be walked through.

  3. The place with number bigger than 1 represents a tree can be walked through, and this positive number represents the tree’s height.

You are asked to cut off all the trees in this forest in the order of tree’s height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).

You will start from the point (0, 0) and you should output the minimum steps you need to walk to cut off all the trees. If you can’t cut off all the trees, output -1 in that situation.

You are guaranteed that no two trees have the same height and there is at least one tree needs to be cut off.

Example 1:

Input:
[
 [1,2,3],
 [0,0,4],
 [7,6,5]
]
Output: 6

Example 2:

Input:
[
 [1,2,3],
 [0,0,0],
 [7,6,5]
]
Output: -1

Example 3:

Input:
[
 [2,3,4],
 [0,0,5],
 [8,7,6]
]
Output: 6
Explanation: You started from the point (0,0) and you can cut off the tree in (0,0) directly without walking.

Hint: size of the given matrix will not exceed 50x50.

1
Unresolved directive in 0675-cut-off-trees-for-golf-event.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0675_CutOffTreesForGolfEvent.java[]

676. Implement Magic Dictionary

Implement a magic directory with buildDict, and search methods.

For the method buildDict, you’ll be given a list of non-repetitive words to build a dictionary.

For the method search, you’ll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.

Example 1:

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False

Note:

  1. You may assume that all the inputs are consist of lowercase letters a-z.

  2. For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.

  3. Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see <a href="https://leetcode.com/faq/#different-output">here</a> for more details.

1
Unresolved directive in 0676-implement-magic-dictionary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0676_ImplementMagicDictionary.java[]

677. Map Sum Pairs

Implement a MapSum class with insert, and sum methods.

For the method insert, you’ll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.

For the method sum, you’ll be given a string representing the prefix, and you need to return the sum of all the pairs' value whose key starts with the prefix.

Example 1:

Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5
1
Unresolved directive in 0677-map-sum-pairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0677_MapSumPairs.java[]

678. Valid Parenthesis String

Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:

  1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.

  2. Any right parenthesis ')' must have a corresponding left parenthesis '('.

  3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.

  4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.

  5. An empty string is also valid.

Example 1:

Input: "()"
Output: True

Example 2:

Input: "()"
Output:* True

Example 3:

Input: "())"
Output:* True

Note:

  1. The string size will be in the range [1, 100].

1
Unresolved directive in 0678-valid-parenthesis-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0678_ValidParenthesisString.java[]

679. 24 Game

You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.

Example 1:

Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: [1, 2, 1, 2]
Output: False

Note:

  1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.

  2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.

  3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.

1
Unresolved directive in 0679-24-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0679_24Game.java[]

680. Valid Palindrome II

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:

Input: "aba"
Output: True

Example 2:

Input: "abca"
Output: True
Explanation: You could delete the character 'c'.

Note:

  1. The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

1
Unresolved directive in 0680-valid-palindrome-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0680_ValidPalindromeII.java[]

681. Next Closest Time

1
Unresolved directive in 0681-next-closest-time.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0681_NextClosestTime.java[]

682. Baseball Game

You’re now a baseball game point recorder.

Given a list of strings, each string can be one of the 4 following types:

  1. Integer (one round’s score): Directly represents the number of points you get in this round.

  2. "+" (one round’s score): Represents that the points you get in this round are the sum of the last two valid round’s points.

  3. "D" (one round’s score): Represents that the points you get in this round are the doubled data of the last valid round’s points.

  4. "C" (an operation, which isn’t a round’s score): Represents the last valid round’s points you get were invalid and should be removed.

Each round’s operation is permanent and could have an impact on the round before and the round after.

You need to return the sum of the points you could get in all the rounds.

Example 1:

Input: ["5","2","C","D","+"]
Output: 30
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get 2 points. The sum is: 7.
Operation 1: The round 2's data was invalid. The sum is: 5.
Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
Round 4: You could get 5 + 10 = 15 points. The sum is: 30.

Example 2:

Input: ["5","-2","4","C","D","9","",""]
Output: 27
Explanation:
Round 1: You could get 5 points. The sum is: 5.
Round 2: You could get -2 points. The sum is: 3.
Round 3: You could get 4 points. The sum is: 7.
Operation 1: The round 3's data is invalid. The sum is: 3.
Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.
Round 5: You could get 9 points. The sum is: 8.
Round 6: You could get -4 + 9 = 5 points. The sum is 13.
Round 7: You could get 9 + 5 = 14 points. The sum is 27.

Note:

  1. The size of the input list will be between 1 and 1000.

  2. Every integer represented in the list will be between -30000 and 30000.

1
Unresolved directive in 0682-baseball-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0682_BaseballGame.java[]

683. K Empty Slots

1
Unresolved directive in 0683-k-empty-slots.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0683_KEmptySlots.java[]

684. Redundant Connection

In this problem, a tree is an undirected graph that is connected and has no cycles.

The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …​, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.

Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v. Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
  1
 / \
2 - 3

Example 2:

Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
    |   |
    4 - 3

Note:

  1. The size of the input 2D-array will be between 3 and 1000.</li>

  2. Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.</li>

<font color="red">Update (2017-09-26): We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directed graph follow up please see <a href="https://leetcode.com/problems/redundant-connection-ii/description/">Redundant Connection II</a>). We apologize for any inconvenience caused.

1
Unresolved directive in 0684-redundant-connection.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0684_RedundantConnection.java[]

685. Redundant Connection II

In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, …​, N), with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.

The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that represents a directed edge connecting nodes u and v, where u is a parent of child v.

Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
  1
 / \
v   v
2-->3

Example 2:

Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
     ^    |
     |    v
     4 <- 3

Note:

  1. The size of the input 2D-array will be between 3 and 1000.</li>

  2. Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.</li>

1
Unresolved directive in 0685-redundant-connection-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0685_RedundantConnectionII.java[]

686. Repeated String Match

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:

The length of A and B will be between 1 and 10000.

1
Unresolved directive in 0686-repeated-string-match.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0686_RepeatedStringMatch.java[]

687. Longest Univalue Path

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5

Output: 2

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5

Output: 2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

1
Unresolved directive in 0687-longest-univalue-path.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0687_LongestUnivaluePath.java[]

688. Knight Probability in Chessboard

On an N`x`N chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).

A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

knight

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.

Example:

Input: 3, 2, 0, 0
Output: 0.0625
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.

Note:

  • N will be between 1 and 25.

  • K will be between 0 and 100.

  • The knight always initially starts on the board.

1
Unresolved directive in 0688-knight-probability-in-chessboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0688_KnightProbabilityInChessboard.java[]

689. Maximum Sum of 3 Non-Overlapping Subarrays

In a given array nums of positive integers, find three non-overlapping subarrays with maximum sum.

Each subarray will be of size k, and we want to maximize the sum of all 3*k entries.

Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.

Example:

Input: [1,2,1,2,6,7,5,1], 2
Output: [0, 3, 5]
Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.

Note:

  • nums.length will be between 1 and 20000.

  • nums[i] will be between 1 and 65535.

  • k will be between 1 and floor(nums.length / 3).

1
Unresolved directive in 0689-maximum-sum-of-3-non-overlapping-subarrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0689_MaximumSumOf3NonOverlappingSubarrays.java[]

690. Employee Importance

You are given a data structure of employee information, which includes the employee’s unique id, his importance value and his direct subordinates' id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

Example 1:

Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.

Note:

  1. One employee has at most one direct leader and may have several subordinates.

  2. The maximum number of employees won’t exceed 2000.

1
Unresolved directive in 0690-employee-importance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0690_EmployeeImportance.java[]

691. Stickers to Spell Word

We are given N different types of stickers. Each sticker has a lowercase English word on it.

You would like to spell out the given target string by cutting individual letters from your collection of stickers and rearranging them.

You can use each sticker more than once if you want, and you have infinite quantities of each sticker.

What is the minimum number of stickers that you need to spell out the target? If the task is impossible, return -1.

Example 1: Input:[subs="verbatim,quotes,macros"]

["with", "example", "science"], "thehat"

Output:[subs="verbatim,quotes,macros"]

3

Explanation:[subs="verbatim,quotes,macros"]

We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.

Example 2: Input:[subs="verbatim,quotes,macros"]

["notice", "possible"], "basicbasic"

Output:[subs="verbatim,quotes,macros"]

-1

Explanation:[subs="verbatim,quotes,macros"]

We can't form the target "basicbasic" from cutting letters from the given stickers.

Note: . stickers has length in the range [1, 50].</li> . stickers consists of lowercase English words (without apostrophes).</li> . target has length in the range [1, 15], and consists of lowercase English letters.</li> . In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.</li> . The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.</li>

1
Unresolved directive in 0691-stickers-to-spell-word.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0691_StickersToSpellWord.java[]

692. Top K Frequent Words

Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

  2. Input words contain only lowercase letters.

Follow up:

  1. Try to solve it in O(n log k) time and O(n) extra space.

1
Unresolved directive in 0692-top-k-frequent-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0692_TopKFrequentWords.java[]

693. Binary Number with Alternating Bits

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.

Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.

Example 4:

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
1
Unresolved directive in 0693-binary-number-with-alternating-bits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0693_BinaryNumberWithAlternatingBits.java[]

694. Number of Distinct Islands

1
Unresolved directive in 0694-number-of-distinct-islands.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0694_NumberOfDistinctIslands.java[]

695. Max Area of Island

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of `1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,1,1,0,1,0,0,0,0,0,0,0,0],
 [0,1,0,0,1,1,0,0,1,0,1,0,0],
 [0,1,0,0,1,1,0,0,1,1,1,0,0],
 [0,0,0,0,0,0,0,0,0,0,1,0,0],
 [0,0,0,0,0,0,0,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

1
Unresolved directive in 0695-max-area-of-island.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0695_MaxAreaOfIsland.java[]

696. Count Binary Substrings

Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0’s and 1’s, and all the 0’s and all the 1’s in these substrings are grouped consecutively.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:

Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

Example 2:

Input: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note: . s.length will be between 1 and 50,000.</li> . s will only consist of "0" or "1" characters.</li>

1
Unresolved directive in 0696-count-binary-substrings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0696_CountBinarySubstrings.java[]

697. Degree of an Array

Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

Example 1:

Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.

Example 2:

Input: [1,2,2,3,1,4,2]
Output: 6

Note: . nums.length will be between 1 and 50,000.</li> . nums[i] will be an integer between 0 and 49,999.</li>

1
Unresolved directive in 0697-degree-of-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0697_DegreeOfAnArray.java[]

698. Partition to K Equal Sum Subsets

Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:

Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.

Note:

  • 1 ⇐ k ⇐ len(nums) ⇐ 16.

  • 0 < nums[i] < 10000.

1
Unresolved directive in 0698-partition-to-k-equal-sum-subsets.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0698_PartitionToKEqualSumSubsets.java[]

699. Falling Squares

On an infinite number line (x-axis), we drop given squares in the order they are given.

The i-th square dropped (positions[i] = (left, side_length)) is a square with the left-most point being positions[i][0] and sidelength positions[i][1].

The square is dropped with the bottom edge parallel to the number line, and from a higher height than all currently landed squares. We wait for each square to stick before dropping the next.

The squares are infinitely sticky on their bottom edge, and will remain fixed to any positive length surface they touch (either the number line or another square). Squares dropped adjacent to each other will not stick together prematurely.

Return a list ans of heights. Each height ans[i] represents the current highest height of any square we have dropped, after dropping squares represented by positions[0], positions[1], …​, positions[i].

Example 1:

Input: [[1, 2], [2, 3], [6, 1]]
Output: [2, 5, 5]
Explanation:

After the first drop of `positions[0] = [1, 2]: _aa _aa ------- `The maximum height of any square is 2.

After the second drop of `positions[1] = [2, 3]: aaa aaa aaa aa _aa_ -------------- `The maximum height of any square is 5. The larger square stays on top of the smaller square despite where its center of gravity is, because squares are infinitely sticky on their bottom edge.

After the third drop of positions[1] = [6, 1]: aaa aaa aaa _aa _aa_a -------------- `The maximum height of any square is still 5. Thus, we return an answer of `[2, 5, 5].

Example 2:

Input: [[100, 100], [200, 100]]
Output: [100, 100]
Explanation: Adjacent squares don't get stuck prematurely - only their bottom edge can stick to surfaces.

Note:

  • 1 ⇐ positions.length ⇐ 1000.

  • 1 ⇐ positions[i][0] ⇐ 10^8.

  • 1 ⇐ positions[i][1] ⇐ 10^6.

1
Unresolved directive in 0699-falling-squares.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0699_FallingSquares.java[]

700. Search in a Binary Search Tree

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node’s value equals the given value. Return the subtree rooted with that node. If such node doesn’t exist, you should return NULL.

For example,

Given the tree:
        4
       / \
      2   7
     / \
    1   3

And the value to search: 2

You should return this subtree:

      2
     / \
    1   3

In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL.

Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null.

1
Unresolved directive in 0700-search-in-a-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0700_SearchInABinarySearchTree.java[]

701. Insert into a Binary Search Tree

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example,

Given the tree:
        4
       / \
      2   7
     / \
    1   3
And the value to insert: 5

You can return this binary search tree:

         4
       /   \
      2     7
     / \   /
    1   3 5

This tree is also valid:

         5
       /   \
      2     7
     / \
    1   3
         \
          4
1
Unresolved directive in 0701-insert-into-a-binary-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0701_InsertIntoABinarySearchTree.java[]

702. Search in a Sorted Array of Unknown Size

1
Unresolved directive in 0702-search-in-a-sorted-array-of-unknown-size.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0702_SearchInASortedArrayOfUnknownSize.java[]

703. Kth Largest Element in a Stream

Design a class to find the *k*th largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3);   // returns 4
kthLargest.add(5);   // returns 5
kthLargest.add(10);  // returns 5
kthLargest.add(9);   // returns 8
kthLargest.add(4);   // returns 8

*Note: *

You may assume that nums’ length ≥ `k-1 and k ≥ 1.

1
Unresolved directive in 0703-kth-largest-element-in-a-stream.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0703_KthLargestElementInAStream.java[]

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Note:

  1. You may assume that all elements in nums are unique.

  2. n will be in the range [1, 10000].

  3. The value of each element in nums will be in the range [-9999, 9999].

1
Unresolved directive in 0704-binary-search.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0704_BinarySearch.java[]

705. Design HashSet

Design a HashSet without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • add(value): Insert a value into the HashSet.

  • contains(value) : Return whether the value exists in the HashSet or not.

  • remove(value): Remove a value in the HashSet. If the value does not exist in the HashSet, do nothing.

Example:

MyHashSet hashSet = new MyHashSet();
hashSet.add(1);
hashSet.add(2);
hashSet.contains(1);    // returns true
hashSet.contains(3);    // returns false (not found)
hashSet.add(2);
hashSet.contains(2);    // returns true
hashSet.remove(2);
hashSet.contains(2);    // returns false (already removed)

Note:

  • All values will be in the range of [0, 1000000].

  • The number of operations will be in the range of [1, 10000].

  • Please do not use the built-in HashSet library.

1
Unresolved directive in 0705-design-hashset.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0705_DesignHashSet.java[]

706. Design HashMap

Design a HashMap without using any built-in hash table libraries.

To be specific, your design should include these functions:

  • put(key, value) : Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.

  • get(key): Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.

  • remove(key) : Remove the mapping for the value key if this map contains the mapping for the key.

Example:

MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1);            // returns 1
hashMap.get(3);            // returns -1 (not found)
hashMap.put(2, 1);          // update the existing value
hashMap.get(2);            // returns 1
hashMap.remove(2);          // remove the mapping for 2
hashMap.get(2);            // returns -1 (not found)

Note:

  • All keys and values will be in the range of [0, 1000000].

  • The number of operations will be in the range of [1, 10000].

  • Please do not use the built-in HashMap library.

1
Unresolved directive in 0706-design-hashmap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0706_DesignHashMap.java[]

707. Design Linked List

Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

Implement these functions in your linked list class:

  • get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.

  • addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.

  • addAtTail(val) : Append a node of value val to the last element of the linked list.

  • addAtIndex(index, val) : Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.

  • deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.

Example:

Input:
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[1],[1]]
Output:
[null,null,null,null,2,null,3]

Explanation:
MyLinkedList linkedList = new MyLinkedList(); // Initialize empty LinkedList
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2);  // linked list becomes 1->2->3
linkedList.get(1);            // returns 2
linkedList.deleteAtIndex(1);  // now the linked list is 1->3
linkedList.get(1);            // returns 3

Constraints:

  • 0 ⇐ index,val ⇐ 1000

  • Please do not use the built-in LinkedList library.

  • At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.

1
Unresolved directive in 0707-design-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0707_DesignLinkedList.java[]

708. Insert into a Sorted Circular Linked List

1
Unresolved directive in 0708-insert-into-a-sorted-circular-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0708_InsertIntoASortedCircularLinkedList.java[]

709. To Lower Case

Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.

Example 1:

Input: "Hello"
Output: "hello"

Example 2:

Input: "here"
Output: "here"

Example 3:

Input: "LOVELY"
Output: "lovely"
1
Unresolved directive in 0709-to-lower-case.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0709_ToLowerCase.java[]

710. Random Pick with Blacklist

Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B.

Optimize it such that it minimizes the call to system’s Math.random().

Note:

  1. 1 ⇐ N ⇐ 1000000000

  2. 0 ⇐ B.length < min(100000, N)

  3. [0, N) does NOT include N. See interval notation.

Example 1:

Input:
 ["Solution","pick","pick","pick"]
 [[1,[]],[],[],[]]
Output: [null,0,0,0]

Example 2:

Input:
 ["Solution","pick","pick","pick"]
 [[2,[]],[],[],[]]
Output: [null,1,1,1]

Example 3:

Input:
 ["Solution","pick","pick","pick"]
 [[3,[1]],[],[],[]]
Output: [null,0,0,2]

Example 4:

Input:
 ["Solution","pick","pick","pick"]
 [[4,[2]],[],[],[]]
Output: [null,1,3,1]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution’s constructor has two arguments, `N and the blacklist B. pick has no arguments. Arguments are always wrapped with a list, even if there aren’t any.

1
Unresolved directive in 0710-random-pick-with-blacklist.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0710_RandomPickWithBlacklist.java[]

711. Number of Distinct Islands II

1
Unresolved directive in 0711-number-of-distinct-islands-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0711_NumberOfDistinctIslandsII.java[]

712. Minimum ASCII Delete Sum for Two Strings

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

Example 1:

Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.

Example 2:

Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d]+101[e]+101[e] to the sum.  Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.

Note: . 0 < s1.length, s2.length ⇐ 1000.</li> . All elements of each string will have an ASCII value in [97, 122].</li>

1
Unresolved directive in 0712-minimum-ascii-delete-sum-for-two-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0712_MinimumASCIIDeleteSumForTwoStrings.java[]

713. Subarray Product Less Than K

Your are given an array of positive integers nums. Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.

Example 1:

Input: nums = [10, 5, 2, 6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Note: . 0 < nums.length ⇐ 50000.</li> . 0 < nums[i] < 1000.</li> . 0 ⇐ k < 10^6.</li>

1
Unresolved directive in 0713-subarray-product-less-than-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0713_SubarrayProductLessThanK.java[]

714. Best Time to Buy and Sell Stock with Transaction Fee

Your are given an array of integers prices, for which the ith element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
 Buying at prices[0] = 1
 Selling at prices[3] = 8
 Buying at prices[4] = 4
 Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:

  • 0 < prices.length ⇐ 50000.

  • 0 < prices[i] < 50000.

  • 0 ⇐ fee < 50000.

参考资料

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.) Return the maximum profit you can make.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
. Buying at prices[0] = 1</li>. Selling at prices[3] = 8</li>. Buying at prices[4] = 4</li>. Selling at prices[5] = 9</li>The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note: . 0 < prices.length ⇐ 50000.</li> . 0 < prices[i] < 50000.</li> . 0 ⇐ fee < 50000.</li>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.diguage.algorithm.leetcode;

/**
 * = 714. Best Time to Buy and Sell Stock with Transaction Fee
 *
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/[Best Time to Buy and Sell Stock with Transaction Fee - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-28 19:48
 */
public class _0714_BestTimeToBuyAndSellStockWithTransactionFee {
    /**
     * Runtime: 3 ms, faster than 100.00% of Java online submissions for Best Time to Buy and Sell Stock with Transaction Fee.
     * Memory Usage: 54.3 MB, less than 27.27% of Java online submissions for Best Time to Buy and Sell Stock with Transaction Fee.
     */
    public int maxProfit(int[] prices, int fee) {
        int dp0 = 0;
        int dp1 = Integer.MIN_VALUE;
        for (int i = 0; i < prices.length; i++) {
            dp0 = Math.max(dp0, dp1 + prices[i]);
            dp1 = Math.max(dp1, dp0 - prices[i] - fee);
        }
        return dp0;
    }

    public static void main(String[] args) {
        _0714_BestTimeToBuyAndSellStockWithTransactionFee solution = new _0714_BestTimeToBuyAndSellStockWithTransactionFee();
        int[] p1 = {1, 3, 2, 8, 4, 9};
        int r1 = solution.maxProfit(p1, 2);
        System.out.println((r1 == 8) + " : " + r1);
    }
}

715. Range Module

A Range Module is a module that tracks ranges of numbers. Your task is to design and implement the following interfaces in an efficient manner.

  1. addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.</li>

  2. queryRange(int left, int right) Returns true if and only if every real number in the interval [left, right) is currently being tracked.</li>

  3. removeRange(int left, int right) Stops tracking every real number currently being tracked in the interval [left, right).</li>

Example 1:

addRange(10, 20): null
removeRange(14, 16): null
queryRange(10, 14): true (Every number in [10, 14) is being tracked)
queryRange(13, 15): false (Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)
queryRange(16, 17): true (The number 16 in [16, 17) is still being tracked, despite the remove operation)

Note: . A half open interval [left, right) denotes all real numbers left ⇐ x < right.</li>

  1. 0 < left < right < 10^9 in all calls to addRange, queryRange, removeRange.</li>

  2. The total number of calls to addRange in a single test case is at most 1000.</li>

  3. The total number of calls to queryRange in a single test case is at most 5000.</li>

  4. The total number of calls to removeRange in a single test case is at most 1000.</li>

1
Unresolved directive in 0715-range-module.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0715_RangeModule.java[]

716. Max Stack

1
Unresolved directive in 0716-max-stack.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0716_MaxStack.java[]

717. 1-bit and 2-bit Characters

We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input:
bits = [1, 0, 0]
Output: True
Explanation:
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

Example 2:

Input:
bits = [1, 1, 1, 0]
Output: False
Explanation:
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

Note: . 1 ⇐ len(bits) ⇐ 1000.</li> . bits[i] is always 0 or 1.</li>

1
Unresolved directive in 0717-1-bit-and-2-bit-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0717_1BitAnd2BitCharacters.java[]

718. Maximum Length of Repeated Subarray

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example 1:

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].

Note:

  1. 1 ⇐ len(A), len(B) ⇐ 1000

  2. 0 ⇐ A[i], B[i] < 100

1
Unresolved directive in 0718-maximum-length-of-repeated-subarray.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0718_MaximumLengthOfRepeatedSubarray.java[]

719. Find K-th Smallest Pair Distance

Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.

Example 1:

Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.

Note:

  1. 2 ⇐ len(nums) ⇐ 10000.

  2. 0 ⇐ nums[i] < 1000000.

  3. 1 ⇐ k ⇐ len(nums) * (len(nums) - 1) / 2.

1
Unresolved directive in 0719-find-k-th-smallest-pair-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0719_FindKThSmallestPairDistance.java[]

720. Longest Word in Dictionary

Given a list of strings words representing an English Dictionary, find the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

Example 1:

Input:
words = ["w","wo","wor","worl", "world"]
Output: "world"
Explanation:
The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".

Example 2:

Input:
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation:
Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".

Note: . All the strings in the input will only contain lowercase letters.</li> . The length of words will be in the range [1, 1000].</li> . The length of words[i] will be in the range [1, 30].</li>

1
Unresolved directive in 0720-longest-word-in-dictionary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0720_LongestWordInDictionary.java[]

721. Accounts Merge

Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.

Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

Example 1:

Input:
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
Explanation:
The first and third John's are the same person as they have the common email "johnsmith@mail.com".
The second John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'],
['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.

Note: . The length of accounts will be in the range [1, 1000].</li> . The length of accounts[i] will be in the range [1, 10].</li> . The length of accounts[i][j] will be in the range [1, 30].</li>

1
Unresolved directive in 0721-accounts-merge.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0721_AccountsMerge.java[]

722. Remove Comments

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.

In C++, there are two types of comments, line comments, and block comments.

The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored.

The string / denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of / should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.

The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.

If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.

There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.)

It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment.

Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.

After removing the comments from the source code, return the source code in the same format.

Example 1:

<pre style="white-space: pre-wrap"> Input: source = ["/Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/ This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]

The line by line code is visualized as below: /Test program */ int main() { // variable declaration int a, b, c; / This is a test multiline comment for testing */ a = b + c; }

Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]

The line by line code is visualized as below: int main() {

int a, b, c; a = b + c; }

Explanation: The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.

*Example 2:*


<pre style="white-space: pre-wrap">
*Input:*
source = ["a/*comment", "line", "more_comment*/b"]
*Output:* ["ab"]
*Explanation:* The original source string is "a/*comment*\n*line*\n*more_comment*/b", where we have bolded the newline characters.  After deletion, the _implicit_ newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].

Note: . The length of source is in the range [1, 100].</li> . The length of source[i] is in the range [0, 80].</li> . Every open block comment is eventually closed.</li> . There are no single-quote, double-quote, or control characters in the source code.</li>

1
Unresolved directive in 0722-remove-comments.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0722_RemoveComments.java[]

723. Candy Crush

1
Unresolved directive in 0723-candy-crush.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0723_CandyCrush.java[]

724. Find Pivot Index

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.

Example 1:

Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.

Example 2:

Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.

Note:

  • The length of nums will be in the range [0, 10000].

  • Each element nums[i] will be an integer in the range [-1000, 1000].

1
Unresolved directive in 0724-find-pivot-index.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0724_FindPivotIndex.java[]

725. Split Linked List in Parts

Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode’s representing the linked list parts that are formed.

Examples 1→2→3→4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Input:
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].

Example 2:

Input:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Note: . The length of root will be in the range [0, 1000].</li> . Each value of a node in the input will be an integer in the range [0, 999].</li> . k will be an integer in the range [1, 50].</li>

1
Unresolved directive in 0725-split-linked-list-in-parts.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0725_SplitLinkedListInParts.java[]

726. Number of Atoms

Given a chemical formula (given as a string), return the count of each atom.

An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.

1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.

Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula.

A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.

Given a formula, output the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.

Example 1:

Input:
formula = "H2O"
Output: "H2O"
Explanation:
The count of elements are {'H': 2, 'O': 1}.

Example 2:

Input:
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation:
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.

Example 3:

Input:
formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation:
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.

Note: . All atom names consist of lowercase letters, except for the first character which is uppercase.</li> . The length of formula will be in the range [1, 1000].</li> . formula will only consist of letters, digits, and round parentheses, and is a valid formula as defined in the problem.</li>

1
Unresolved directive in 0726-number-of-atoms.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0726_NumberOfAtoms.java[]

727. Minimum Window Subsequence

1
Unresolved directive in 0727-minimum-window-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0727_MinimumWindowSubsequence.java[]

728. Self Dividing Numbers

A self-dividing number is a number that is divisible by every digit it contains.

For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.

Also, a self-dividing number is not allowed to contain the digit zero.

Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.

Example 1:

Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]

Note: . The boundaries of each input argument are 1 ⇐ left ⇐ right ⇐ 10000.</li>

1
Unresolved directive in 0728-self-dividing-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0728_SelfDividingNumbers.java[]

729. My Calendar I

Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking.

Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start ⇐ x < end.

A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)

For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar. Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)

Example 1:

MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(15, 25); // returns false
MyCalendar.book(20, 30); // returns true
Explanation:
The first event can be booked.  The second can't because time 15 is already booked by another event.
The third event can be booked, as the first event takes every time less than 20, but not including 20.

Note:

  • The number of calls to MyCalendar.book per test case will be at most 1000.

  • In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].

1
Unresolved directive in 0729-my-calendar-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0729_MyCalendarI.java[]

730. Count Different Palindromic Subsequences

Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7.

A subsequence of a string S is obtained by deleting 0 or more characters from S.

A sequence is palindromic if it is equal to the sequence reversed.

Two sequences A_1, A_2, …​ and B_1, B_2, …​ are different if there is some i for which A_i != B_i.

Example 1:

Input:
S = 'bccb'
Output: 6
Explanation:
The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.

Example 2:

Input:
S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
Output: 104860361
Explanation:
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.

Note: . The length of S will be in the range [1, 1000].</li> . Each character S[i] will be in the set {'a', 'b', 'c', 'd'}.</li>

1
Unresolved directive in 0730-count-different-palindromic-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0730_CountDifferentPalindromicSubsequences.java[]

731. My Calendar II

Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.

Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start ⇐ x < end.

A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)

For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar. Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)

Example 1:

MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(50, 60); // returns true
MyCalendar.book(10, 40); // returns true
MyCalendar.book(5, 15); // returns false
MyCalendar.book(5, 10); // returns true
MyCalendar.book(25, 55); // returns true
Explanation:
The first two events can be booked.  The third event can be double booked.
The fourth event (5, 15) can't be booked, because it would result in a triple booking.
The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event;
the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.

Note:

  • The number of calls to MyCalendar.book per test case will be at most 1000.

  • In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].

1
Unresolved directive in 0731-my-calendar-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0731_MyCalendarII.java[]

732. My Calendar III

Implement a MyCalendarThree class to store your events. A new event can always be added.

Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start ⇐ x < end.

A K-booking happens when K events have some non-empty intersection (ie., there is some time that is common to all K events.)

For each call to the method MyCalendar.book, return an integer K representing the largest integer such that there exists a K-booking in the calendar. Your class will be called like this: MyCalendarThree cal = new MyCalendarThree(); MyCalendarThree.book(start, end)

Example 1:

MyCalendarThree();
MyCalendarThree.book(10, 20); // returns 1
MyCalendarThree.book(50, 60); // returns 1
MyCalendarThree.book(10, 40); // returns 2
MyCalendarThree.book(5, 15); // returns 3
MyCalendarThree.book(5, 10); // returns 3
MyCalendarThree.book(25, 55); // returns 3
Explanation:
The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking.
The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking.
The remaining events cause the maximum K-booking to be only a 3-booking.
Note that the last event locally causes a 2-booking, but the answer is still 3 because
eg. [10, 20), [10, 40), and [5, 15) are still triple booked.

Note:

  • The number of calls to MyCalendarThree.book per test case will be at most 400.

  • In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9].

1
Unresolved directive in 0732-my-calendar-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0732_MyCalendarIII.java[]

733. Flood Fill

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.

To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.

Example 1:

Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.

Note: . The length of image and image[0] will be in the range [1, 50].</li> . The given starting pixel will satisfy 0 ⇐ sr < image.length and 0 ⇐ sc < image[0].length.</li> . The value of each color in image[i][j] and newColor will be an integer in [0, 65535].</li>

1
Unresolved directive in 0733-flood-fill.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0733_FloodFill.java[]

734. Sentence Similarity

1
Unresolved directive in 0734-sentence-similarity.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0734_SentenceSimilarity.java[]

735. Asteroid Collision

We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Example 1:

Input:
asteroids = [5, 10, -5]
Output: [5, 10]
Explanation:
The 10 and -5 collide resulting in 10.  The 5 and 10 never collide.

Example 2:

Input:
asteroids = [8, -8]
Output: []
Explanation:
The 8 and -8 collide exploding each other.

Example 3:

Input:
asteroids = [10, 2, -5]
Output: [10]
Explanation:
The 2 and -5 collide resulting in -5.  The 10 and -5 collide resulting in 10.

Example 4:

Input:
asteroids = [-2, -1, 1, 2]
Output: [-2, -1, 1, 2]
Explanation:
The -2 and -1 are moving left, while the 1 and 2 are moving right.
Asteroids moving the same direction never meet, so no asteroids will meet each other.

Note: . The length of asteroids will be at most 10000.</li> . Each asteroid will be a non-zero integer in the range [-1000, 1000]..</li>

1
Unresolved directive in 0735-asteroid-collision.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0735_AsteroidCollision.java[]

736. Parse Lisp Expression

You are given a string expression representing a Lisp-like expression to return the integer value of.

The syntax for these expressions is given as follows.

  1. An expression is either an integer, a let-expression, an add-expression, a mult-expression, or an assigned variable. Expressions always evaluate to a single integer.</li>

  2. (An integer could be positive or negative.)</li>

  3. A let-expression takes the form (let v1 e1 v2 e2 …​ vn en expr), where let is always the string "let", then there are 1 or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let-expression is the value of the expression expr.</li>

  4. An add-expression takes the form (add e1 e2) where add is always the string "add", there are always two expressions e1, e2, and this expression evaluates to the addition of the evaluation of e1 and the evaluation of e2.</li>

  5. A mult-expression takes the form (mult e1 e2) where mult is always the string "mult", there are always two expressions e1, e2, and this expression evaluates to the multiplication of the evaluation of e1 and the evaluation of e2.</li>

  6. For the purposes of this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally for your convenience, the names "add", "let", or "mult" are protected and will never be used as variable names.</li>

  7. Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on scope.</li>

Evaluation Examples:

Input: (add 1 2)
Output: 3

Input: (mult 3 (add 2 3))
Output: 15

Input: (let x 2 (mult x 5))
Output: 10

Input: (let x 2 (mult x (let x 3 y 4 (add x y))))
Output: 14
Explanation: In the expression (add x y), when checking for the value of the variable x,
we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.
Since x = 3 is found first, the value of x is 3.

Input: (let x 3 x 2 x)
Output: 2
Explanation: Assignment in let statements is processed sequentially.

Input: (let x 1 y 2 x (add x y) (add x y))
Output: 5
Explanation: The first (add x y) evaluates as 3, and is assigned to x.
The second (add x y) evaluates as 3+2 = 5.

Input: (let x 2 (add (let x 3 (let x 4 x)) x))
Output: 6
Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
of the final x in the add-expression.  That final x will equal 2.

Input: (let a1 3 b2 (add a1 1) b2)
Output 4
Explanation: Variable names can contain digits after the first character.

Note: . The given string expression is well formatted: There are no leading or trailing spaces, there is only a single space separating different components of the string, and no space between adjacent parentheses. The expression is guaranteed to be legal and evaluate to an integer.</li> . The length of expression is at most 2000. (It is also non-empty, as that would not be a legal expression.)</li> . The answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.</li>

1
Unresolved directive in 0736-parse-lisp-expression.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0736_ParseLispExpression.java[]

737. Sentence Similarity II

1
Unresolved directive in 0737-sentence-similarity-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0737_SentenceSimilarityII.java[]

738. Monotone Increasing Digits

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x ⇐ y.)

Example 1:

Input: N = 10
Output: 9

Example 2:

Input: N = 1234
Output: 1234

Example 3:

Input: N = 332
Output: 299

Note: N is an integer in the range [0, 10^9].

1
Unresolved directive in 0738-monotone-increasing-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0738_MonotoneIncreasingDigits.java[]

739. Daily Temperatures

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

1
Unresolved directive in 0739-daily-temperatures.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0739_DailyTemperatures.java[]

740. Delete and Earn

Given an array nums of integers, you can perform operations on the array.

In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.

You start with 0 points. Return the maximum number of points you can earn by applying such operations.

Example 1:

Input: nums = [3, 4, 2]
Output: 6
Explanation:
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.

Example 2:

Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.

Note:

  • The length of nums is at most 20000.

  • Each element nums[i] is an integer in the range [1, 10000].

1
Unresolved directive in 0740-delete-and-earn.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0740_DeleteAndEarn.java[]

741. Cherry Pickup

In a N x N grid representing a field of cherries, each cell is one of three possible integers.

  • 0 means the cell is empty, so you can pass through;

  • 1 means the cell contains a cherry, that you can pick up and pass through;

  • -1 means the cell contains a thorn that blocks your way.

Your task is to collect maximum number of cherries possible by following the rules below:

  • Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);

  • After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;

  • When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);

  • If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.

Example 1:

Input: grid =
[[0, 1, -1],
 [1, 0, -1],
 [1, 1,  1]]
Output: 5
Explanation:
The player started at (0, 0) and went down, down, right right to reach (2, 2).
4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
Then, the player went left, up, up, left to return home, picking up one more cherry.
The total number of cherries picked up is 5, and this is the maximum possible.

Note:

  • grid is an N by N 2D array, with 1 ⇐ N ⇐ 50.

  • Each grid[i][j] is an integer in the set {-1, 0, 1}.

  • It is guaranteed that grid[0][0] and grid[N-1][N-1] are not -1. *

1
Unresolved directive in 0741-cherry-pickup.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0741_CherryPickup.java[]

742. Closest Leaf in a Binary Tree

1
Unresolved directive in 0742-closest-leaf-in-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0742_ClosestLeafInABinaryTree.java[]

743. Network Delay Time

There are N network nodes, labelled 1 to N.

Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.

Example 1:

931 example 1
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2

Note:

  1. N will be in the range [1, 100].

  2. K will be in the range [1, N].

  3. The length of times will be in the range [1, 6000].

  4. All edges times[i] = (u, v, w) will have 1 ⇐ u, v ⇐ N and 0 ⇐ w ⇐ 100.

1
Unresolved directive in 0743-network-delay-time.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0743_NetworkDelayTime.java[]

744. Find Smallest Letter Greater Than Target

Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target.

Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'.

Examples:

Input:
letters = ["c", "f", "j"]
target = "a"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "c"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "d"
Output: "f"

Input:
letters = ["c", "f", "j"]
target = "g"
Output: "j"

Input:
letters = ["c", "f", "j"]
target = "j"
Output: "c"

Input:
letters = ["c", "f", "j"]
target = "k"
Output: "c"

Note:

  1. letters has a length in range [2, 10000].

  2. letters consists of lowercase letters, and contains at least 2 unique letters.

  3. target is a lowercase letter.

1
Unresolved directive in 0744-find-smallest-letter-greater-than-target.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0744_FindSmallestLetterGreaterThanTarget.java[]

Given many words, words[i] has weight i.

Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.

Examples:

Input:
WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1

Note:

  1. words has length in range [1, 15000].

  2. For each test case, up to words.length queries WordFilter.f may be made.

  3. words[i] has length in range [1, 10].

  4. prefix, suffix have lengths in range [0, 10].

  5. words[i] and prefix, suffix queries consist of lowercase letters only.

1
Unresolved directive in 0745-prefix-and-suffix-search.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0745_PrefixAndSuffixSearch.java[]

746. Min Cost Climbing Stairs

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Note:

  1. cost will have a length in the range [2, 1000].

  2. Every cost[i] will be an integer in the range [0, 999].

1
Unresolved directive in 0746-min-cost-climbing-stairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0746_MinCostClimbingStairs.java[]

747. Largest Number At Least Twice of Others

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise return -1.

Example 1:

Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer, and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.

Note:

  1. nums will have a length in the range [1, 50].

  2. Every nums[i] will be an integer in the range [0, 99].

1
Unresolved directive in 0747-largest-number-at-least-twice-of-others.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0747_LargestNumberAtLeastTwiceOfOthers.java[]

748. Shortest Completing Word

Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate

Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.

It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.

The license plate might have the same letter occurring multiple times. For example, given a licensePlate of "PP", the word "pair" does not complete the licensePlate, but the word "supper" does.

Example 1:

Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
Output: "steps"
Explanation: The smallest length word that contains the letters "S", "P", "S", and "T".
Note that the answer is not "step", because the letter "s" must occur in the word twice.
Also note that we ignored case for the purposes of comparing whether a letter exists in the word.

Example 2:

Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
Output: "pest"
Explanation: There are 3 smallest length words that contains the letters "s".
We return the one that occurred first.

Note:

  1. licensePlate will be a string with length in range [1, 7].

  2. licensePlate will contain digits, spaces, or letters (uppercase or lowercase).

  3. words will have a length in the range [10, 1000].

  4. Every words[i] will consist of lowercase letters, and have length in range [1, 15].

1
Unresolved directive in 0748-shortest-completing-word.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0748_ShortestCompletingWord.java[]

749. Contain Virus

A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.

The world is modeled as a 2-D array of cells, where 0 represents uninfected cells, and 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.

Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region — the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night. There will never be a tie.

Can you save the day? If so, what is the number of walls required? If not, and the world becomes fully infected, return the number of walls used.

Example 1:

Input: grid =
[[0,1,0,0,0,0,0,1],
 [0,1,0,0,0,0,0,1],
 [0,0,0,0,0,0,0,1],
 [0,0,0,0,0,0,0,0]]
Output: 10
Explanation:
There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:

[[0,1,0,0,0,0,1,1],
 [0,1,0,0,0,0,1,1],
 [0,0,0,0,0,0,1,1],
 [0,0,0,0,0,0,0,1]]

On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.

Example 2:

Input: grid =
[[1,1,1],
 [1,0,1],
 [1,1,1]]
Output: 4
Explanation: Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.

Example 3:

Input: grid =
[[1,1,1,0,0,0,0,0,0],
 [1,0,1,0,1,1,1,1,1],
 [1,1,1,0,0,0,0,0,0]]
Output: 13
Explanation: The region on the left only builds two new walls.

Note:

  1. The number of rows and columns of grid will each be in the range [1, 50].

  2. Each grid[i][j] will be either 0 or 1.

  3. Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.

1
Unresolved directive in 0749-contain-virus.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0749_ContainVirus.java[]

750. Number Of Corner Rectangles

1
Unresolved directive in 0750-number-of-corner-rectangles.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0750_NumberOfCornerRectangles.java[]

751. IP to CIDR

1
Unresolved directive in 0751-ip-to-cidr.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0751_IPToCIDR.java[]

752. Open the Lock

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

Example 1:

Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Output: 6
Explanation:
A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102".

Example 2:

Input: deadends = ["8888"], target = "0009"
Output: 1
Explanation:
We can turn the last wheel in reverse to move from "0000" -> "0009".

Example 3:

Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
Output: -1
Explanation:
We can't reach the target without getting stuck.

Example 4:

Input: deadends = ["0000"], target = "8888"
Output: -1

Note:

  1. The length of deadends will be in the range [1, 500].

  2. target will not be in the list deadends.

  3. Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'.

1
Unresolved directive in 0752-open-the-lock.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0752_OpenTheLock.java[]

753. Cracking the Safe

There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, …​, k-1.

While entering a password, the last n digits entered will automatically be matched against the correct password.

For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the suffix of the entered password.

Return any password of minimum length that is guaranteed to open the box at some point of entering it.

Example 1:

Input: n = 1, k = 2
Output: "01"
Note: "10" will be accepted too.

Example 2:

Input: n = 2, k = 2
Output: "00110"
Note: "01100", "10011", "11001" will be accepted too.

Note:

  1. n will be in the range [1, 4].

  2. k will be in the range [1, 10].

  3. k^n will be at most 4096.

1
Unresolved directive in 0753-cracking-the-safe.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0753_CrackingTheSafe.java[]

754. Reach a Number

You are standing at position 0 on an infinite number line. There is a goal at position target.

On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.

Return the minimum number of steps required to reach the destination.

Example 1:

Input: target = 3
Output: 2
Explanation:
On the first move we step from 0 to 1.
On the second step we step from 1 to 3.

Example 2:

Input: target = 2
Output: 3
Explanation:
On the first move we step from 0 to 1.
On the second move we step  from 1 to -1.
On the third move we step from -1 to 2.

Note: . target will be a non-zero integer in the range [-10^9, 10^9].</li>

1
Unresolved directive in 0754-reach-a-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0754_ReachANumber.java[]

755. Pour Water

1
Unresolved directive in 0755-pour-water.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0755_PourWater.java[]

756. Pyramid Transition Matrix

We are stacking blocks to form a pyramid. Each block has a color which is a one letter string.

We are allowed to place any color block C on top of two adjacent blocks of colors A and B, if and only if ABC is an allowed triple.

We start with a bottom row of bottom, represented as a single string. We also start with a list of allowed triples allowed. Each allowed triple is represented as a string of length 3.

Return true if we can build the pyramid all the way to the top, otherwise false.

Example 1:

Input: bottom = "BCD", allowed = ["BCG", "CDE", "GEA", "FFF"]
Output: true
Explanation:
We can stack the pyramid like this:
    A
   / \
  G   E
 / \ / \
B   C   D

We are allowed to place G on top of B and C because BCG is an allowed triple.  Similarly, we can place E on top of C and D, then A on top of G and E.

Example 2:

Input: bottom = "AABA", allowed = ["AAA", "AAB", "ABA", "ABB", "BAC"]
Output: false
Explanation:
We can't stack the pyramid to the top.
Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.

Note:

  1. bottom will be a string with length in range [2, 8].

  2. allowed will have length in range [0, 200].

  3. Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}.

1
Unresolved directive in 0756-pyramid-transition-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0756_PyramidTransitionMatrix.java[]

757. Set Intersection Size At Least Two

An integer interval [a, b] (for integers a < b) is a set of all consecutive integers from a to b, including a and b.

Find the minimum size of a set S such that for every integer interval A in intervals, the intersection of S with A has size at least 2.

Example 1:

Input: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
Output: 3
Explanation:
Consider the set S = {2, 3, 4}.  For each interval, there are at least 2 elements from S in the interval.
Also, there isn't a smaller size set that fulfills the above condition.
Thus, we output the size of this set, which is 3.

Example 2:

Input: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
Output: 5
Explanation:
An example of a minimum sized set is {1, 2, 3, 4, 5}.

Note: . intervals will have length in range [1, 3000]. . intervals[i] will have length 2, representing some integer interval. . intervals[i][j] will be an integer in [0, 10^8].

1
Unresolved directive in 0757-set-intersection-size-at-least-two.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0757_SetIntersectionSizeAtLeastTwo.java[]

758. Bold Words in String

1
Unresolved directive in 0758-bold-words-in-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0758_BoldWordsInString.java[]

759. Employee Free Time

1
Unresolved directive in 0759-employee-free-time.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0759_EmployeeFreeTime.java[]

760. Find Anagram Mappings

1
Unresolved directive in 0760-find-anagram-mappings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0760_FindAnagramMappings.java[]

761. Special Binary String

Special binary strings are binary strings with the following two properties:

  1. The number of 0’s is equal to the number of 1’s.

  2. Every prefix of the binary string has at least as many 1’s as 0’s.

Given a special string S, a move consists of choosing two consecutive, non-empty, special substrings of S, and swapping them. (Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.)

At the end of any number of moves, what is the lexicographically largest resulting string possible?

Example 1:

Input: S = "11011000"
Output: "11100100"
Explanation:
The strings "10" [occuring at S[1]] and "1100" [at S[3]] are swapped.
This is the lexicographically largest string possible after some number of swaps.

Note: . S has length at most 50. . S is guaranteed to be a special binary string as defined above.

1
Unresolved directive in 0761-special-binary-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0761_SpecialBinaryString.java[]

762. Prime Number of Set Bits in Binary Representation

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.

(Recall that the number of set bits an integer has is the number of 1`s present when written in binary. For example, `21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)

Example 1:

Input: L = 6, R = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)

Example 2:

Input: L = 10, R = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)

Note: . L, R will be integers L ⇐ R in the range [1, 10^6]. . R - L will be at most 10000.

1
Unresolved directive in 0762-prime-number-of-set-bits-in-binary-representation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0762_PrimeNumberOfSetBitsInBinaryRepresentation.java[]

763. Partition Labels

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.

Note: . S will have length in range [1, 500]. . S will consist of lowercase letters ('a' to 'z') only.

1
Unresolved directive in 0763-partition-labels.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0763_PartitionLabels.java[]

764. Largest Plus Sign

In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0. What is the largest axis-aligned plus sign of `1`s contained in the grid? Return the order of the plus sign. If there is none, return 0.

An "axis-aligned plus sign of 1`s of order k" has some center `grid[x][y] = 1 along with 4 arms of length k-1 going up, down, left, and right, and made of `1`s. This is demonstrated in the diagrams below. Note that there could be `0`s or `1`s beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1s.

Examples of Axis-Aligned Plus Signs of Order k:

Order 1:
000
010
000

Order 2:
00000
00100
01110
00100
00000

Order 3:
0000000
0001000
0001000
0111110
0001000
0001000
0000000

Example 1:

Input: N = 5, mines = [[4, 2]]
Output: 2
Explanation:
11111
11111
11111
11111
11011
In the above grid, the largest plus sign can only be order 2.  One of them is marked in bold.

Example 2:

Input: N = 2, mines = []
Output: 1
Explanation:
There is no plus sign of order 2, but there is of order 1.

Example 3:

Input: N = 1, mines = [[0, 0]]
Output: 0
Explanation:
There is no plus sign, so return 0.

Note: . N will be an integer in the range [1, 500]. . mines will have length at most 5000. . mines[i] will be length 2 and consist of integers in the range [0, N-1]. . (Additionally, programs submitted in C, C++, or C# will be judged with a slightly smaller time limit.)

1
Unresolved directive in 0764-largest-plus-sign.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0764_LargestPlusSign.java[]

765. Couples Holding Hands

N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.

The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1).

The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat.

Example 1:

Input: row = [0, 2, 1, 3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.

Example 2:

Input: row = [3, 2, 0, 1]
Output: 0
Explanation: All couples are already seated side by side.

Note:

  1. len(row) is even and in the range of [4, 60].

  2. row is guaranteed to be a permutation of 0…​len(row)-1.

1
Unresolved directive in 0765-couples-holding-hands.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0765_CouplesHoldingHands.java[]

766. Toeplitz Matrix

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

Example 1:

Input:
matrix = [
  [1,2,3,4],
  [5,1,2,3],
  [9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input:
matrix = [
  [1,2],
  [2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.

Note:

  1. matrix will be a 2D array of integers.

  2. matrix will have a number of rows and columns in range [1, 20].

  3. matrix[i][j] will be integers in range [0, 99].

Follow up:

  1. What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?

  2. What if the matrix is so large that you can only load up a partial row into the memory at once?

1
Unresolved directive in 0766-toeplitz-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0766_ToeplitzMatrix.java[]

767. Reorganize String

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

1
Unresolved directive in 0767-reorganize-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0767_ReorganizeString.java[]

768. Max Chunks To Make Sorted II

This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8.

<hr />

Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

Example 1:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.

Example 2:

Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

Note:

  • arr will have length in range [1, 2000].

  • arr[i] will be an integer in range [0, 10**8].

1
Unresolved directive in 0768-max-chunks-to-make-sorted-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0768_MaxChunksToMakeSortedII.java[]

769. Max Chunks To Make Sorted

Given an array arr that is a permutation of [0, 1, …​, arr.length - 1], we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array.

What is the most number of chunks we could have made?

Example 1:

Input: arr = [4,3,2,1,0]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.

Example 2:

Input: arr = [1,0,2,3,4]
Output: 4
Explanation:
We can split into two chunks, such as [1, 0], [2, 3, 4].
However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.

Note:

  • arr will have length in range [1, 10].

  • arr[i] will be a permutation of [0, 1, …​, arr.length - 1].

1
Unresolved directive in 0769-max-chunks-to-make-sorted.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0769_MaxChunksToMakeSorted.java[]

770. Basic Calculator IV

Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]

  • An expression alternates chunks and symbols, with a space separating each chunk and symbol.

  • A chunk is either an expression in parentheses, a variable, or a non-negative integer.

  • A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".

Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, expression = "1 + 2 * 3" has an answer of ["7"].

The format of the output is as follows:

  • For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like "b*a*c", only "a*b*c".

  • Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, "a*a*b*c" has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.

  • The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.

  • An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]

  • Terms (including constant terms) with coefficient 0 are not included. For example, an expression of "0" has an output of [].

Examples:

Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]

Input: expression = "e - 8 + temperature - pressure",
evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]

Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]

Input: expression = "7 - 7", evalvars = [], evalints = []
Output: []

Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
Output: ["5*a*b*c"]

Input: expression = "a - b) * (b - c) + (c - a * a - b) + (b - c) * (c - a",
evalvars = [], evalints = []
Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]

Note:

  • expression will have length in range [1, 250].

  • evalvars, evalints will have equal lengths in range [0, 100].

1
Unresolved directive in 0770-basic-calculator-iv.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0770_BasicCalculatorIV.java[]

771. Jewels and Stones

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".

Example 1:

Input: J = "aA", S = "aAAbbbb"
Output: 3

Example 2:

Input: J = "z", S = "ZZ"
Output: 0

Note:

  • S and J will consist of letters and have length at most 50.

  • The characters in J are distinct.

1
Unresolved directive in 0771-jewels-and-stones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0771_JewelsAndStones.java[]

772. Basic Calculator III

1
Unresolved directive in 0772-basic-calculator-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0772_BasicCalculatorIII.java[]

773. Sliding Puzzle

On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.

A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

Examples:

Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Input: board = [[3,2,4],[1,5,0]]
Output: 14

Note:

  • board will be a 2 x 3 array as described above.

  • board[i][j] will be a permutation of [0, 1, 2, 3, 4, 5].

1
Unresolved directive in 0773-sliding-puzzle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0773_SlidingPuzzle.java[]

774. Minimize Max Distance to Gas Station

1
Unresolved directive in 0774-minimize-max-distance-to-gas-station.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0774_MinimizeMaxDistanceToGasStation.java[]

775. Global and Local Inversions

We have some permutation A of [0, 1, …​, N - 1], where N is the length of A.

The number of (global) inversions is the number of i < j with 0 ⇐ i < j < N and A[i] > A[j].

The number of local inversions is the number of i with 0 ⇐ i < N and A[i] > A[i+1].

Return true if and only if the number of global inversions is equal to the number of local inversions.

Example 1:

Input: A = [1,0,2]
Output: true
Explanation: There is 1 global inversion, and 1 local inversion.

Example 2:

Input: A = [1,2,0]
Output: false
Explanation: There are 2 global inversions, and 1 local inversion.

Note:

  • A will be a permutation of [0, 1, …​, A.length - 1].

  • A will have length in range [1, 5000].

  • The time limit for this problem has been reduced.

1
Unresolved directive in 0775-global-and-local-inversions.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0775_GlobalAndLocalInversions.java[]

776. Split BST

1
Unresolved directive in 0776-split-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0776_SplitBST.java[]

777. Swap Adjacent in LR String

In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.

Example:

Input: start = "RXXLRXRXL", end = "XRLXXRRLX"
Output: True
Explanation:
We can transform start to end following these steps:
RXXLRXRXL ->
XRXLRXRXL ->
XRLXRXRXL ->
XRLXXRRXL ->
XRLXXRRLX

Note:

  1. 1 ⇐ len(start) = len(end) ⇐ 10000.

  2. Both start and end will only consist of characters in {'L', 'R', 'X'}.

1
Unresolved directive in 0777-swap-adjacent-in-lr-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0777_SwapAdjacentInLRString.java[]

778. Swim in Rising Water

On an N x N grid, each square grid[i][j] represents the elevation at that point (i,j).

Now rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distance in zero time. Of course, you must stay within the boundaries of the grid during your swim.

You start at the top left square (0, 0). What is the least time until you can reach the bottom right square (N-1, N-1)?

Example 1:

Input: [[0,2],[1,3]]
Output: 3
Explanation:
At time 0, you are in grid location (0, 0).
You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.

You cannot reach point (1, 1) until time 3.
When the depth of water is 3, we can swim anywhere inside the grid.

Example 2:

Input: [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output: 16
Explanation:
 0  1  2  3  4
24 23 22 21  5
12 13 14 15 16
11 17 18 19 20
10  9  8  7  6

The final route is marked in bold.
We need to wait until time 16 so that (0, 0) and (4, 4) are connected.

Note:

  1. 2 ⇐ N ⇐ 50.

  2. grid[i][j] is a permutation of [0, …​, N*N - 1].

1
Unresolved directive in 0778-swim-in-rising-water.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0778_SwimInRisingWater.java[]

779. K-th Symbol in Grammar

On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).

Examples:
Input: N = 1, K = 1
Output: 0

Input: N = 2, K = 1
Output: 0

Input: N = 2, K = 2
Output: 1

Input: N = 4, K = 5
Output: 1

Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001

Note:

  1. N will be an integer in the range [1, 30].

  2. K will be an integer in the range [1, 2^(N-1)].

1
Unresolved directive in 0779-k-th-symbol-in-grammar.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0779_KThSymbolInGrammar.java[]

780. Reaching Points

A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

Given a starting point (sx, sy) and a target point (tx, ty), return True if and only if a sequence of moves exists to transform the point (sx, sy) to (tx, ty). Otherwise, return False.

Examples:
Input: sx = 1, sy = 1, tx = 3, ty = 5
Output: True
Explanation:
One series of moves that transforms the starting point to the target is:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)

Input: sx = 1, sy = 1, tx = 2, ty = 2
Output: False

Input: sx = 1, sy = 1, tx = 1, ty = 1
Output: True

Note:

  • sx, sy, tx, ty will all be integers in the range [1, 10^9].

1
Unresolved directive in 0780-reaching-points.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0780_ReachingPoints.java[]

781. Rabbits in Forest

In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

Return the minimum number of rabbits that could be in the forest.

Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0

Note:

  1. answers will have length at most 1000.

  2. Each answers[i] will be an integer in the range [0, 999].

1
Unresolved directive in 0781-rabbits-in-forest.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0781_RabbitsInForest.java[]

782. Transform to Chessboard

An N x N board contains only `0`s and `1`s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.

What is the minimum number of moves to transform the board into a "chessboard" - a board where no `0`s and no `1`s are 4-directionally adjacent? If the task is impossible, return -1.

Examples:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output: 2
Explanation:
One potential sequence of moves is shown below, from left to right:

0110     1010     1010
0110 --> 1010 --> 0101
1001     0101     1010
1001     0101     0101

The first move swaps the first and second column.
The second move swaps the second and third row.


Input: board = [[0, 1], [1, 0]]
Output: 0
Explanation:
Also note that the board with 0 in the top left corner,
01
10

is also a valid chessboard.

Input: board = [[1, 0], [1, 0]]
Output: -1
Explanation:
No matter what sequence of moves you make, you cannot end with a valid chessboard.

Note:

  • board will have the same number of rows and columns, a number in the range [2, 30].

  • board[i][j] will be only `0`s or `1`s.

1
Unresolved directive in 0782-transform-to-chessboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0782_TransformToChessboard.java[]

783. Minimum Distance Between BST Nodes

Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

Example :

Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.

The given tree [4,2,6,1,3,null,null] is represented by the following diagram:

          4
        /   \
      2      6
     / \
    1   3

while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.

Note:

  1. The size of the BST will be between 2 and 100.

  2. The BST is always valid, each node’s value is an integer, and each node’s value is different.

1
Unresolved directive in 0783-minimum-distance-between-bst-nodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0783_MinimumDistanceBetweenBSTNodes.java[]

784. Letter Case Permutation

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.

Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]

Note:

  • S will be a string with length between 1 and 12.

  • S will consist only of letters or digits.

1
Unresolved directive in 0784-letter-case-permutation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0784_LetterCasePermutation.java[]

785. Is Graph Bipartite?

Given an undirected graph, return true if and only if it is bipartite.

Recall that a graph is bipartite if we can split it’s set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.

The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn’t contain any element twice.

Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation:
The graph looks like this:
0----1
|    |
|    |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation:
The graph looks like this:
0----1
| \  |
|  \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.

Note:

  • graph will have length in range [1, 100].

  • graph[i] will contain integers in range [0, graph.length - 1].

  • graph[i] will not contain i or duplicate values.

  • The graph is undirected: if any element j is in graph[i], then i will be in graph[j].

1
Unresolved directive in 0785-is-graph-bipartite.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0785_IsGraphBipartite.java[]

786. K-th Smallest Prime Fraction

A sorted list A contains 1, plus some number of primes. Then, for every p < q in the list, we consider the fraction p/q.

What is the K-th smallest fraction considered? Return your answer as an array of ints, where answer[0] = p and answer[1] = q.

Examples:
Input: A = [1, 2, 3, 5], K = 3
Output: [2, 5]
Explanation:
The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, 2/3.
The third fraction is 2/5.

Input: A = [1, 7], K = 1
Output: [1, 7]

Note:

  • A will have length between 2 and 2000.

  • Each A[i] will be between 1 and 30000.

  • K will be between 1 and A.length * (A.length - 1) / 2.

1
Unresolved directive in 0786-k-th-smallest-prime-fraction.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0786_KThSmallestPrimeFraction.java[]

787. Cheapest Flights Within K Stops

There are n cities connected by m flights. Each fight starts from city u `and arrives at `v with a price w.

Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.

Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" alt="995">

The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" alt="995">

The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.

Note:

  • The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n` - 1`.

  • The size of flights will be in range [0, n * (n - 1) / 2].

  • The format of each flight will be (src, dst, price).

  • The price of each flight will be in the range [1, 10000].

  • k is in the range of [0, n - 1].

  • There will not be any duplicated flights or self cycles.

1
Unresolved directive in 0787-cheapest-flights-within-k-stops.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0787_CheapestFlightsWithinKStops.java[]

788. Rotated Digits

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Example:
Input: 10
Output: 4
Explanation:
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Note:

  • N will be in range [1, 10000].

1
Unresolved directive in 0788-rotated-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0788_RotatedDigits.java[]

789. Escape The Ghosts

You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is` (target[0], target[1]). There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1])`.

Each turn, you and all ghosts simultaneously may move in one of 4 cardinal directions: north, east, west, or south, going from the previous point to a new point 1 unit of distance away.

You escape if and only if you can reach the target before any ghost reaches you (for any given moves the ghosts may take.) If you reach any square (including the target) at the same time as a ghost, it doesn’t count as an escape.

Return True if and only if it is possible to escape.

Example 1:
Input:
ghosts = [[1, 0], [0, 3]]
target = [0, 1]
Output: true
Explanation:
You can directly reach the destination (0, 1) at time 1, while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you.
Example 2:
Input:
ghosts = [[1, 0]]
target = [2, 0]
Output: false
Explanation:
You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
Example 3:
Input:
ghosts = [[2, 0]]
target = [1, 0]
Output: false
Explanation:
The ghost can reach the target at the same time as you.

Note:

  • All points have coordinates with absolute value ⇐ 10000.

  • The number of ghosts will not exceed 100.

1
Unresolved directive in 0789-escape-the-ghosts.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0789_EscapeTheGhosts.java[]

790. Domino and Tromino Tiling

We have two types of tiles: a 2x1 domino shape, and an "L" tromino shape. These shapes may be rotated.

XX  <- domino

XX  <- "L" tromino
X

Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.

(In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.)

Example:
Input: 3
Output: 5
Explanation:
The five different ways are listed below, different letters indicates different tiles:
XYZ XXZ XYY XXY XYY
XYZ YYZ XZZ XYY XXY

Note:

  • N will be in range [1, 1000].

1
Unresolved directive in 0790-domino-and-tromino-tiling.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0790_DominoAndTrominoTiling.java[]

791. Custom Sort String

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

Note:

  • S has length at most 26, and no character is repeated in S.

  • T has length at most 200.

  • S and T consist of lowercase letters only.

1
Unresolved directive in 0791-custom-sort-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0791_CustomSortString.java[]

792. Number of Matching Subsequences

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Example :
Input:
S = "abcde"
words = ["a", "bb", "acd", "ace"]
Output: 3
Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace".

Note:

  • All words in words and S will only consists of lowercase letters.

  • The length of S will be in the range of [1, 50000].

  • The length of words will be in the range of [1, 5000].

  • The length of words[i] will be in the range of [1, 50].

1
Unresolved directive in 0792-number-of-matching-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0792_NumberOfMatchingSubsequences.java[]

793. Preimage Size of Factorial Zeroes Function

Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * …​ * x, and by convention, 0! = 1.)

For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.

Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.

Note:

  • K will be an integer in the range [0, 10^9].

1
Unresolved directive in 0793-preimage-size-of-factorial-zeroes-function.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0793_PreimageSizeOfFactorialZeroesFunction.java[]

794. Valid Tic-Tac-Toe State

A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a 3 x 3 array, and consists of characters " ", "X", and "O". The " " character represents an empty square.

Here are the rules of Tic-Tac-Toe:

  • Players take turns placing characters into empty squares (" ").

  • The first player always places "X" characters, while the second player always places "O" characters.

  • "X" and "O" characters are always placed into empty squares, never filled ones.

  • The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.

  • The game also ends if all squares are non-empty.

  • No more moves can be played if the game is over.

Example 1:
Input: board = ["O  ", "   ", "   "]
Output: false
Explanation: The first player always plays "X".

Example 2:
Input: board = ["XOX", " X ", "   "]
Output: false
Explanation: Players take turns making moves.

Example 3:
Input: board = ["XXX", "   ", "OOO"]
Output: false

Example 4:
Input: board = ["XOX", "O O", "XOX"]
Output: true

Note:

  • board is a length-3 array of strings, where each string board[i] has length 3.

  • Each board[i][j] is a character in the set {" ", "X", "O"}.

1
Unresolved directive in 0794-valid-tic-tac-toe-state.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0794_ValidTicTacToeState.java[]

795. Number of Subarrays with Bounded Maximum

We are given an array A of positive integers, and two positive integers L and R (L ⇐ R).

Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least L and at most R.

Example :
Input:
A = [2, 1, 4, 3]
L = 2
R = 3
Output: 3
Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].

Note:

  • L, R and A[i] will be an integer in the range [0, 10^9].

  • The length of A will be in the range of [1, 50000].

1
Unresolved directive in 0795-number-of-subarrays-with-bounded-maximum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0795_NumberOfSubarraysWithBoundedMaximum.java[]

796. Rotate String

We are given two strings, A and B.

A shift on A` consists of taking string `A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.

Example 1:
Input: A = 'abcde', B = 'cdeab'
Output: true

Example 2:
Input: A = 'abcde', B = 'abced'
Output: false

Note:

  • A and B will have length at most 100.

1
Unresolved directive in 0796-rotate-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0796_RotateString.java[]

797. All Paths From Source to Target

Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.

The graph is given as follows: the nodes are 0, 1, …​, graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.

Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
|    |
v    v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

Note:

  • The number of nodes in the graph will be in the range [2, 15].

  • You can print different paths in any order, but you should keep the order of nodes inside one path.

1
Unresolved directive in 0797-all-paths-from-source-to-target.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0797_AllPathsFromSourceToTarget.java[]

798. Smallest Rotation with Highest Score

Given an array `A`, we may rotate it by a non-negative integer `K` so that the array becomes `A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1]`.  Afterward, any entries that are less than or equal to their index are worth 1 point.

For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2, it becomes [1, 3, 0, 2, 4]. This is worth 3 points because 1 > 0 [no points], 3 > 1 [no points], 0 ⇐ 2 [one point], 2 ⇐ 3 [one point], 4 ⇐ 4 [one point].

Over all possible rotations, return the rotation index K that corresponds to the highest score we could receive. If there are multiple answers, return the smallest such index K.

Example 1:
Input: [2, 3, 1, 4, 0]
Output: 3
Explanation:
Scores for each K are listed below:
K = 0,  A = [2,3,1,4,0],    score 2
K = 1,  A = [3,1,4,0,2],    score 3
K = 2,  A = [1,4,0,2,3],    score 3
K = 3,  A = [4,0,2,3,1],    score 4
K = 4,  A = [0,2,3,1,4],    score 3

So we should choose K = 3, which has the highest score.

Example 2:
Input: [1, 3, 0, 2, 4]
Output: 0
Explanation: A will always have 3 points no matter how it shifts.
So we will choose the smallest K, which is 0.

Note:

  • A will have length at most 20000.

  • A[i] will be in the range [0, A.length].

1
Unresolved directive in 0798-smallest-rotation-with-highest-score.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0798_SmallestRotationWithHighestScore.java[]

799. Champagne Tower

We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup (250ml) of champagne.

Then, some champagne is poured in the first glass at the top. When the top most glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has it’s excess champagne fall on the floor.)

For example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.

tower

Now after pouring some non-negative integer cups of champagne, return how full the j-th glass in the i-th row is (both i and j are 0 indexed.)

Example 1:
Input: poured = 1, query_glass = 1, query_row = 1
Output: 0.0
Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.

Example 2:
Input: poured = 2, query_glass = 1, query_row = 1
Output: 0.5
Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.

Note:

  • poured will be in the range of [0, 10 ^ 9].

  • query_glass and query_row will be in the range of [0, 99].

1
Unresolved directive in 0799-champagne-tower.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0799_ChampagneTower.java[]

800. Similar RGB Color

1
Unresolved directive in 0800-similar-rgb-color.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0800_SimilarRGBColor.java[]

801. Minimum Swaps To Make Sequences Increasing

We have two integer sequences A and B of the same non-zero length.

We are allowed to swap elements A[i] and B[i]. Note that both elements are in the same index position in their respective sequences.

At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < …​ < A[A.length - 1].)

Given A and B, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible.

Example:
Input: A = [1,3,5,4], B = [1,2,3,7]
Output: 1
Explanation:
Swap A[3] and B[3].  Then the sequences are:
A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
which are both strictly increasing.

Note:

  • A, B are arrays with the same length, and that length will be in the range [1, 1000].

  • A[i], B[i] are integer values in the range [0, 2000].

1
Unresolved directive in 0801-minimum-swaps-to-make-sequences-increasing.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0801_MinimumSwapsToMakeSequencesIncreasing.java[]

802. Find Eventual Safe States

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is _eventually safe _if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe? Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, …​, N-1, where N is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.
picture1

Note:

  • graph will have length at most 10000.

  • The number of edges in the graph will not exceed 32000.

  • Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1].

1
Unresolved directive in 0802-find-eventual-safe-states.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0802_FindEventualSafeStates.java[]

803. Bricks Falling When Hit

We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only if it is directly connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.

We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), the brick (if it exists) on that location will disappear, and then some other bricks may drop because of that erasure.

Return an array representing the number of bricks that will drop after each erasure in sequence.

Example 1:
Input:
grid = [[1,0,0,0],[1,1,1,0]]
hits = [[1,0]]
Output: [2]
Explanation:
If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.
Example 2:
Input:
grid = [[1,0,0,0],[1,1,0,0]]
hits = [[1,1],[1,0]]
Output: [0,0]
Explanation:
When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. So each erasure will cause no bricks dropping.  Note that the erased brick (1, 0) will not be counted as a dropped brick.

Note:

  • The number of rows and columns in the grid will be in the range [1, 200].

  • The number of erasures will not exceed the area of the grid.

  • It is guaranteed that each erasure will be different from any other erasure, and located inside the grid.

  • An erasure may refer to a location with no brick - if it does, no bricks drop.

1
Unresolved directive in 0803-bricks-falling-when-hit.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0803_BricksFallingWhenHit.java[]

804. Unique Morse Code Words

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-…​", "c" maps to "-.-.", and so on.

For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, "cba" can be written as "-.-..--…​", (which is the concatenation "-.-." + "-…​" + ".-"). We’ll call such a concatenation, the transformation of a word.

Return the number of different transformations among all words we have.

Example:
Input: words = ["gin", "zen", "gig", "msg"]
Output: 2
Explanation:
The transformation of each word is:
"gin" -> "--...-."
"zen" -> "--...-."
"gig" -> "--...--."
"msg" -> "--...--."

There are 2 different transformations, "--...-." and "--...--.".

Note:

  • The length of words will be at most 100.

  • Each words[i] will have length in range [1, 12].

  • words[i] will only consist of lowercase letters.

1
Unresolved directive in 0804-unique-morse-code-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0804_UniqueMorseCodeWords.java[]

805. Split Array With Same Average

In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)

Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.

Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.

Note:

  • The length of A will be in the range [1, 30].

  • A[i] will be in the range of [0, 10000].

1
Unresolved directive in 0805-split-array-with-same-average.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0805_SplitArrayWithSameAverage.java[]

806. Number of Lines To Write String

We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths, an array where widths[0] is the width of 'a', widths[1] is the width of 'b', …​, and widths[25] is the width of 'z'.

Now answer two questions: how many lines have at least one character from S, and what is the width used by the last such line? Return your answer as an integer list of length 2.

Example :
Input:
widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "abcdefghijklmnopqrstuvwxyz"
Output: [3, 60]
Explanation:
All letters have the same length of 10. To write all 26 letters,
we need two full lines and one line with 60 units.
Example :
Input:
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "bbbcccdddaaa"
Output: [2, 4]
Explanation:
All letters except 'a' have the same length of 10, and
"bbbcccdddaa" will cover 9  10 + 2  4 = 98 units.
For the last 'a', it is written on the second line because
there is only 2 units left in the first line.
So the answer is 2 lines, plus 4 units in the second line.

Note:

  • The length of S will be in the range [1, 1000].

  • S will only contain lowercase letters.

  • widths is an array of length 26.

  • widths[i] will be in the range of [2, 10].

1
Unresolved directive in 0806-number-of-lines-to-write-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0806_NumberOfLinesToWriteString.java[]

807. Max Increase to Keep City Skyline

In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.

At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city’s skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.

What is the maximum total sum that the height of the buildings can be increased?

Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
  [2, 4, 5, 7],
  [9, 2, 6, 3],
  [0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew = [ [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3] ]

*Notes: *

  • 1 < grid.length = grid[0].length ⇐ 50.

  • All heights grid[i][j] are in the range [0, 100].

  • All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.

1
Unresolved directive in 0807-max-increase-to-keep-city-skyline.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0807_MaxIncreaseToKeepCitySkyline.java[]

808. Soup Servings

There are two types of soup: type A and type B. Initially we have N ml of each type of soup. There are four kinds of operations:

  • Serve 100 ml of soup A and 0 ml of soup B

  • Serve 75 ml of soup A and 25 ml of soup B

  • Serve 50 ml of soup A and 50 ml of soup B

  • Serve 25 ml of soup A and 75 ml of soup B

When we serve some soup, we give it to someone and we no longer have it. Each turn, we will choose from the four operations with equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as we can. We stop once we no longer have some quantity of both types of soup.

Note that we do not have the operation where all 100 ml’s of soup B are used first.

Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time.

Example:
Input: N = 50
Output: 0.625
Explanation:
If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.

*Notes: *

  • 0 ⇐ N ⇐ 10^9.

  • Answers within 10^-6 of the true value will be accepted as correct.

1
Unresolved directive in 0808-soup-servings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0808_SoupServings.java[]

809. Expressive Words

Sometimes people repeat letters to represent extra feeling, such as "hello" → "heeellooo", "hi" → "hiiii". In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo".

For some given string S, a query word is stretchy if it can be made to be equal to S by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is 3 or more.

For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has size less than 3. Also, we could do another extension like "ll" → "lllll" to get "helllllooo". If S = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" → "hellooo" → "helllllooo" = S.

Given a list of query words, return the number of words that are stretchy.

Example:
Input:
S = "heeellooo"
words = ["hello", "hi", "helo"]
Output: 1
Explanation:
We can extend "e" and "o" in the word "hello" to get "heeellooo".
We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.

*Notes: *

  • 0 ⇐ len(S) ⇐ 100.

  • 0 ⇐ len(words) ⇐ 100.

  • 0 ⇐ len(words[i]) ⇐ 100.

  • S and all words in words consist only of lowercase letters

1
Unresolved directive in 0809-expressive-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0809_ExpressiveWords.java[]

810. Chalkboard XOR Game

We are given non-negative integers nums[i] which are written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. (Also, we’ll say the bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.)

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example:
Input: nums = [1, 1, 2]
Output: false
Explanation:
Alice has two choices: erase 1 or erase 2.
If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose.
If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.

*Notes: *

  • 1 ⇐ N ⇐ 1000.

  • 0 ⇐ nums[i] ⇐ 2^16.

1
Unresolved directive in 0810-chalkboard-xor-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0810_ChalkboardXORGame.java[]

811. Subdomain Visit Count

A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.

Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".

We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

Example 1:
Input:
["9001 discuss.leetcode.com"]
Output:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation:
We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Example 2:
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.

*Notes: *

  • The length of cpdomains will not exceed 100.

  • The length of each domain name will not exceed 100.

  • Each address will have either 1 or 2 "." characters.

  • The input count in any count-paired domain will not exceed 10000.

  • The answer output can be returned in any order.

1
Unresolved directive in 0811-subdomain-visit-count.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0811_SubdomainVisitCount.java[]

812. Largest Triangle Area

You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.

Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
1027

*Notes: *

  • 3 ⇐ points.length ⇐ 50.

  • No points will be duplicated.

  • -50 ⇐ points[i][j] ⇐ 50.

  • Answers within 10^-6 of the true value will be accepted as correct.

1
Unresolved directive in 0812-largest-triangle-area.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0812_LargestTriangleArea.java[]

813. Largest Sum of Averages

We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?

Note that our partition must use every number in A, and that scores are not necessarily integers.

Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation:
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.

*Note: *

  • 1 ⇐ A.length ⇐ 100.

  • 1 ⇐ A[i] ⇐ 10000.

  • 1 ⇐ K ⇐ A.length.

  • Answers within 10^-6 of the correct answer will be accepted as correct.

1
Unresolved directive in 0813-largest-sum-of-averages.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0813_LargestSumOfAverages.java[]

814. Binary Tree Pruning

We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.

Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

Example 1:
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]

Explanation:
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" alt="1028 2">
Example 2:
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]


:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" alt="1028 1">
Example 3:
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]


:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" alt="1028">

*Note: *

  • The binary tree will have at most 100 nodes.

  • The value of each node will only be 0 or 1.

1
Unresolved directive in 0814-binary-tree-pruning.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0814_BinaryTreePruning.java[]

815. Bus Routes

We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1→5→7→1→5→7→1→…​ forever.

We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.

Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

*Note: *

  • 1 ⇐ routes.length ⇐ 500.

  • 1 ⇐ routes[i].length ⇐ 500.

  • 0 ⇐ routes[i][j] < 10 ^ 6.

1
Unresolved directive in 0815-bus-routes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0815_BusRoutes.java[]

816. Ambiguous Coordinates

We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces, and ended up with the string S. Return a list of strings representing all possibilities for what our original coordinates could have been.

Our original representation never had extraneous zeroes, so we never started with numbers like "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like ".1".

The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)

Example 1:
Input: "(123)"
Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"]
Example 2:
Input: "(00011)"
Output:  ["(0.001, 1)", "(0, 0.011)"]
Explanation:
0.0, 00, 0001 or 00.01 are not allowed.
Example 3:
Input: "(0123)"
Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"]
Example 4:
Input: "(100)"
Output: [(10, 0)]
Explanation:
1.0 is not allowed.

*Note: *

  • 4 ⇐ S.length ⇐ 12.

  • S[0] = "(", S[S.length - 1] = ")", and the other elements in S are digits.

1
Unresolved directive in 0816-ambiguous-coordinates.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0816_AmbiguousCoordinates.java[]

817. Linked List Components

We are given head, the head node of a linked list containing unique integer values.

We are also given the list G, a subset of the values in the linked list.

Return the number of connected components in G, where two values are connected if they appear consecutively in the linked list.

Example 1:

Input:
head: 0->1->2->3
G = [0, 1, 3]
Output: 2
Explanation:
0 and 1 are connected, so [0, 1] and [3] are the two connected components.

Example 2:

Input:
head: 0->1->2->3->4
G = [0, 3, 1, 4]
Output: 2
Explanation:
0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.

*Note: *

  • If N is the length of the linked list given by head, 1 ⇐ N ⇐ 10000.

  • The value of each node in the linked list will be in the range` [0, N - 1]`.

  • 1 ⇐ G.length ⇐ 10000.

  • G is a subset of all values in the linked list.

1
Unresolved directive in 0817-linked-list-components.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0817_LinkedListComponents.java[]

818. Race Car

Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)

Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).

When you get an instruction "A", your car does the following: position += speed, speed *= 2.

When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1. (Your position stays the same.)

For example, after commands "AAR", your car goes to positions 0→1→3→3, and your speed goes to 1→2→4→-1.

Now for some target position, say the length of the shortest sequence of instructions to get there.

Example 1:
Input:
target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0->1->3.
Example 2:
Input:
target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0->1->3->7->7->6.

*Note: *

  • 1 ⇐ target ⇐ 10000.

1
Unresolved directive in 0818-race-car.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0818_RaceCar.java[]

819. Most Common Word

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

Example:

Input:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.

*Note: *

  • 1 ⇐ paragraph.length ⇐ 1000.

  • 0 ⇐ banned.length ⇐ 100.

  • 1 ⇐ banned[i].length ⇐ 10.

  • The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)

  • paragraph only consists of letters, spaces, or the punctuation symbols !?',;.

  • There are no hyphens or hyphenated words.

  • Words only consist of letters, never apostrophes or other punctuation symbols.

1
Unresolved directive in 0819-most-common-word.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0819_MostCommonWord.java[]

820. Short Encoding of Words

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.

For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].

Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character.

What is the length of the shortest reference string S possible that encodes the given words?

Example:

Input: words = ["time", "me", "bell"]
Output: 10
Explanation: S = "time#bell#" and indexes = [0, 2, 5].

Note:

  1. 1 ⇐ words.length ⇐ 2000.

  2. 1 ⇐ words[i].length ⇐ 7.

  3. Each word has only lowercase letters.

1
Unresolved directive in 0820-short-encoding-of-words.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0820_ShortEncodingOfWords.java[]

821. Shortest Distance to a Character

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example 1:

Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

Note:

  1. S string length is in [1, 10000].

  2. C is a single character, and guaranteed to be in string S.

  3. All letters in S and C are lowercase.

1
Unresolved directive in 0821-shortest-distance-to-a-character.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0821_ShortestDistanceToACharacter.java[]

822. Card Flipping Game

On a table are N cards, with a positive integer printed on the front and back of each card (possibly different).

We flip any number of cards, and after we choose one card.

If the number X on the back of the chosen card is not on the front of any card, then this number X is good.

What is the smallest number that is good? If no number is good, output 0.

Here, fronts[i] and backs[i] represent the number on the front and back of card i.

A flip swaps the front and back numbers, so the value on the front is now on the back and vice versa.

Example:

Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]
Output: 2
Explanation: If we flip the second card, the fronts are [1,3,4,4,7] and the backs are [1,2,4,1,3].
We choose the second card, which has number 2 on the back, and it isn't on the front of any card, so 2 is good.

Note:

  1. 1 ⇐ fronts.length == backs.length ⇐ 1000.

  2. 1 ⇐ fronts[i] ⇐ 2000.

  3. 1 ⇐ backs[i] ⇐ 2000.

1
Unresolved directive in 0822-card-flipping-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0822_CardFlippingGame.java[]

823. Binary Trees With Factors

Given an array of unique integers, each integer is strictly greater than 1.

We make a binary tree using these integers and each number may be used for any number of times.

Each non-leaf node’s value should be equal to the product of the values of it’s children.

How many binary trees can we make? Return the answer modulo 10 * 9 + 7*.

Example 1:

Input: A = [2, 4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]

Example 2:

Input: A = [2, 4, 5, 10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].

Note:

  1. 1 ⇐ A.length ⇐ 1000.

  2. 2 ⇐ A[i] ⇐ 10 ^ 9.

1
Unresolved directive in 0823-binary-trees-with-factors.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0823_BinaryTreesWithFactors.java[]

824. Goat Latin

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:

Input: "I speak Goat Latin"
Output: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"

Example 2:

Input: "The quick brown fox jumped over the lazy dog"
Output: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"

Notes:

  • S contains only uppercase, lowercase and spaces. Exactly one space between each word.

  • 1 ⇐ S.length ⇐ 150.

1
Unresolved directive in 0824-goat-latin.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0824_GoatLatin.java[]

825. Friends Of Appropriate Ages

Some people will make friend requests. The list of their ages is given and ages[i] is the age of the ith person.

Person A will NOT friend request person B (B != A) if any of the following conditions are true:

  • age[B] ⇐ 0.5 * age[A] + 7

  • age[B] > age[A]

  • age[B] > 100 && age[A] < 100

Otherwise, A will friend request B.

Note that if A requests B, B does not necessarily request A. Also, people will not friend request themselves.

How many total friend requests are made?

Example 1:

Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.

Example 2:

Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.

Example 3:

Input: [20,30,100,110,120]
Output:
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.

Notes:

  • 1 ⇐ ages.length ⇐ 20000.

  • 1 ⇐ ages[i] ⇐ 120.

1
Unresolved directive in 0825-friends-of-appropriate-ages.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0825_FriendsOfAppropriateAges.java[]

826. Most Profit Assigning Work

We have jobs: difficulty[i] is the difficulty of the i`th job, and `profit[i] is the profit of the `i`th job.

Now we have some workers. worker[i] is the ability of the i`th worker, which means that this worker can only complete a job with difficulty at most `worker[i].

Every worker can be assigned at most one job, but one job can be completed multiple times.

For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.

What is the most profit we can make?

Example 1:

Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.

Notes:

  • 1 ⇐ difficulty.length = profit.length ⇐ 10000

  • 1 ⇐ worker.length ⇐ 10000

  • difficulty[i], profit[i], worker[i] are in range [1, 10^5]

1
Unresolved directive in 0826-most-profit-assigning-work.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0826_MostProfitAssigningWork.java[]

827. Making A Large Island

In a 2D grid of 0`s and `1`s, we change at most one `0 to a 1.

After, what is the size of the largest island? (An island is a 4-directionally connected group of `1`s).

Example 1:

Input: [[1, 0], [0, 1]]
Output: 3
Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.

Example 2:

Input: [[1, 1], [1, 0]]
Output: 4
Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.

Example 3:

Input: [[1, 1], [1, 1]]
Output: 4
Explanation: Can't change any 0 to 1, only one island with area = 4.

Notes:

  • 1 ⇐ grid.length = grid[0].length ⇐ 50.

  • 0 ⇐ grid[i][j] ⇐ 1.

1
Unresolved directive in 0827-making-a-large-island.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0827_MakingALargeIsland.java[]

828. Unique Letter String

A character is unique in string S if it occurs exactly once in it.

For example, in string S = "LETTER", the only unique characters are "L" and "R".

Let’s define UNIQ(S) as the number of unique characters in string S.

For example, UNIQ("LETTER") = 2.

Given a string S with only uppercases, calculate the sum of UNIQ(substring) over all non-empty substrings of S.

If there are two or more equal substrings at different positions in S, we consider them different.

Since the answer can be very large, return the answer modulo 10 ^ 9 + 7.

Example 1:

Input: "ABC"
Output: 10
Explanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".
Evey substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10

Example 2:

Input: "ABA"
Output: 8
Explanation: The same as example 1, except uni("ABA") = 1.

Note: 0 ⇐ S.length ⇐ 10000.

1
Unresolved directive in 0828-unique-letter-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0828_UniqueLetterString.java[]

829. Consecutive Numbers Sum

Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3

Example 2:

Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4

Example 3:

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

Note: 1 ⇐ N ⇐ 10 ^ 9.

1
Unresolved directive in 0829-consecutive-numbers-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0829_ConsecutiveNumbersSum.java[]

830. Positions of Large Groups

In a string S of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".

Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.

The final answer should be in lexicographic order.

Example 1:

Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting  3 and ending positions 6.

Example 2:

Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.

Example 3:

Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]

*Note: * 1 ⇐ S.length ⇐ 1000

1
Unresolved directive in 0830-positions-of-large-groups.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0830_PositionsOfLargeGroups.java[]

831. Masking Personal Information

We are given a personal information string S, which may represent either an email address or a phone number.

We would like to mask this personal information according to the following rules:

1. Email address:

We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z.

An email address starts with a name, followed by the symbol '@', followed by a name, followed by the dot '.' and followed by a name.

All email addresses are guaranteed to be valid and in the format of "name1@name2.name3".

To mask an email, all names must be converted to lowercase and all letters between the first and last letter of the first name must be replaced by 5 asterisks '*'.

2. Phone number:

A phone number is a string consisting of only the digits 0-9 or the characters from the set {'+', '-', '(', ')', ' '}. You may assume a phone number contains 10 to 13 digits.

The last 10 digits make up the local number, while the digits before those make up the country code. Note that the country code is optional. We want to expose only the last 4 digits and mask all other digits.

The local number should be formatted and masked as "--1111", `where `1 represents the exposed digits.

To mask a phone number with country code like "+111 111 111 1111", we write it in the form "+--*-1111". The '+' sign and the first '-' sign before the local number should only exist if there is a country code. For example, a 12 digit phone number mask should start with "+-".

Note that extraneous characters like "(", ")", " ", as well as extra dashes or plus signs not part of the above formatting scheme should be removed.

Return the correct "mask" of the information provided.

Example 1:

Input: "LeetCode@LeetCode.com"
Output: "le@leetcode.com"
Explanation: All names are converted to lowercase, and the letters between the
             first and last letter of the first name is replaced by 5 asterisks.
             Therefore, "leetcode" -> "le".

Example 2:

Input: "AB@qq.com"
Output: "ab@qq.com"
Explanation: There must be 5 asterisks between the first and last letter
             of the first name "ab". Therefore, "ab" -> "ab".

Example 3:

Input: "1(234)567-890"
Output: "--7890"
Explanation: 10 digits in the phone number, which means all digits make up the local number.

Example 4:

Input: "86-(10)12345678"
Output: "+--*-5678"
Explanation:* 12 digits, 2 digits for country code and 10 digits for local number.

Notes:

  1. S.length ⇐ 40.

  2. Emails have length at least 8.

  3. Phone numbers have length at least 10.

1
Unresolved directive in 0831-masking-personal-information.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0831_MaskingPersonalInformation.java[]

832. Flipping an Image

Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed. For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0. For example, inverting [0, 1, 1] results in [1, 0, 0].

Example 1:

Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the " alt="[1" width="0" height="0">,[0,1,0],[1,1,1]]

Example 2:

Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].
Then invert the " alt="[1" width="1" height="0">,[0,1,1,0],[0,0,0,1],[1,0,1,0]]

Notes:

  • 1 ⇐ A.length = A[0].length ⇐ 20

  • 0 ⇐ A[i][j]<font face="sans-serif, Arial, Verdana, Trebuchet MS"> ⇐ 1

1
Unresolved directive in 0832-flipping-an-image.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0832_FlippingAnImage.java[]

833. Find And Replace in String

To some string S, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).

Each replacement operation has 3 parameters: a starting index i, a source word x and a target word y. The rule is that if <font face="monospace">x starts at position i in the original string S, then we will replace that occurrence of x with y. If not, we do nothing.

For example, if we have S = "abcd" and we have some replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position <font face="monospace">2 in the original string S, we will replace it with "ffff".

Using another example on S = "abcd", if we have both the replacement operation i = 0, x = "ab", y = "eee", as well as another replacement operation i = 2, x = "ec", y = "ffff", this second operation does nothing because in the original string S[2] = 'c', which doesn’t match x[0] = 'e'.

All these operations occur simultaneously. It’s guaranteed that there won’t be any overlap in replacement: for example, S = "abc", indexes = [0, 1], sources = ["ab","bc"] is not a valid test case.

Example 1:

Input: S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
Output: "eeebffff"
Explanation: "a" starts at index 0 in S, so it's replaced by "eee".
"cd" starts at index 2 in S, so it's replaced by "ffff".

Example 2:

Input: S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
Output: "eeecd"
Explanation: "ab" starts at index 0 in S, so it's replaced by "eee".
"ec" doesn't starts at index 2 in the original S, so we do nothing.

Notes:

  1. 0 ⇐ indexes.length = sources.length = targets.length ⇐ 100

  2. 0 < indexes[i] < S.length ⇐ 1000

  3. All characters in given inputs are lowercase letters.

1
Unresolved directive in 0833-find-and-replace-in-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0833_FindAndReplaceInString.java[]

834. Sum of Distances in Tree

An undirected, connected tree with N nodes labelled 0…​N-1 and N-1 edges are given.

The i`th edge connects nodes `edges[i][0] `and edges[i][1]` together.

Return a list ans, where ans[i] is the sum of the distances between node i and all other nodes.

Example 1:

Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation:
Here is a diagram of the given tree:
  0
 / \
1   2
   /|\
  3 4 5
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
equals 1 + 1 + 2 + 2 + 2 = 8.  Hence, answer[0] = 8, and so on.

Note:<font face="monospace"> 1 ⇐ N ⇐ 10000

1
Unresolved directive in 0834-sum-of-distances-in-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0834_SumOfDistancesInTree.java[]

835. Image Overlap

Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.

(Note also that a translation does not include any kind of rotation.)

What is the largest possible overlap?

Example 1:

Input: A = [[1,1,0],
            [0,1,0],
            [0,1,0]]
       B = [[0,0,0],
            [0,1,1],
            [0,0,1]]
Output: 3
Explanation: We slide A to right by 1 unit and down by 1 unit.

Notes:

  1. 1 ⇐ A.length = A[0].length = B.length = B[0].length ⇐ 30

  2. 0 ⇐ A[i][j], B[i][j] ⇐ 1

1
Unresolved directive in 0835-image-overlap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0835_ImageOverlap.java[]

836. Rectangle Overlap

A rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) are the coordinates of its bottom-left corner, and (x2, y2) are the coordinates of its top-right corner.

Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.

Given two (axis-aligned) rectangles, return whether they overlap.

Example 1:

Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]
Output: true

Example 2:

Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]
Output: false

Notes:

  1. Both rectangles rec1 and rec2 are lists of 4 integers.

  2. All coordinates in rectangles will be between -10^9 `and 10^9`.

1
Unresolved directive in 0836-rectangle-overlap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0836_RectangleOverlap.java[]

837. New 21 Game

Alice plays the following game, loosely based on the card game "21".

Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities.

Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points?

Example 1:

Input: N = 10, K = 1, W = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.

Example 2:

Input: N = 6, K = 1, W = 10
Output: 0.60000
Explanation: Alice gets a single card, then stops.
In 6 out of W = 10 possibilities, she is at or below N = 6 points.

Example 3:

Input: N = 21, K = 17, W = 10
Output: 0.73278

Note:

  1. 0 ⇐ K ⇐ N ⇐ 10000

  2. 1 ⇐ W ⇐ 10000

  3. Answers will be accepted as correct if they are within 10^-5 of the correct answer.

  4. The judging time limit has been reduced for this question.

1
Unresolved directive in 0837-new-21-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0837_New21Game.java[]

838. Push Dominoes

There are<font face="monospace"> N dominoes in a line, and we place each domino vertically upright.

In the beginning, we simultaneously push some of the dominoes either to the left or to the right.

domino

After each second, each domino that is falling to the left pushes the adjacent domino on the left.

Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.

When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.

For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.

Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.

Return a string representing the final state.

Example 1:

Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."

Example 2:

Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.

Note:

  1. 0 ⇐ N ⇐ 10^5

  2. String dominoes contains only 'L’, ’R' and '.'

1
Unresolved directive in 0838-push-dominoes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0838_PushDominoes.java[]

839. Similar String Groups

Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.

For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar to "tars", "rats", or "arts".

Together, these form two connected groups by similarity: {"tars", "rats", "arts"} and {"star"}. Notice that "tars" and "arts" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.

We are given a list A of strings. Every string in A is an anagram of every other string in A. How many groups are there?

Example 1:

Input: A = ["tars","rats","arts","star"]
Output: 2

Constraints:

  • 1 ⇐ A.length ⇐ 2000

  • 1 ⇐ A[i].length ⇐ 1000

  • A.length * A[i].length ⇐ 20000

  • All words in A consist of lowercase letters only.

  • All words in A have the same length and are anagrams of each other.

  • The judging time limit has been increased for this question.

1
Unresolved directive in 0839-similar-string-groups.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0839_SimilarStringGroups.java[]

840. Magic Squares In Grid

A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.

Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).

Example 1:

Input: [[4,3,8,4],
        [9,5,1,9],
        [2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:
438
951
276

while this one is not:
384
519
762

In total, there is only one magic square inside the given grid.

Note:

  1. 1 ⇐ grid.length ⇐ 10

  2. 1 ⇐ grid[0].length ⇐ 10

  3. 0 ⇐ grid[i][j] ⇐ 15

1
Unresolved directive in 0840-magic-squares-in-grid.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0840_MagicSquaresInGrid.java[]

841. Keys and Rooms

There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, …​, N-1, and each room may have some keys to access the next room.

Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, …​, N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v.

Initially, all the rooms start locked (except for room 0).

You can walk back and forth between rooms freely.

Return true if and only if you can enter every room.

Example 1:

Input: [[1],[2],[3],[]]
Output: true
Explanation:  
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.  Since we were able to go to every room, we return true.

Example 2:

Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

  1. 1 ⇐ rooms.length ⇐ 1000

  2. 0 ⇐ rooms[i].length ⇐ 1000

  3. The number of keys in all rooms combined is at most 3000.

1
Unresolved directive in 0841-keys-and-rooms.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0841_KeysAndRooms.java[]

842. Split Array into Fibonacci Sequence

Given a string S of digits, such as S = "123456579", we can split it into a Fibonacci-like sequence [123, 456, 579].

Formally, a Fibonacci-like sequence is a list F of non-negative integers such that:

  • 0 ⇐ F[i] ⇐ 2^31 - 1, (that is, each integer fits a 32-bit signed integer type);

  • F.length >= 3;

  • and` F[i] + F[i+1] = F[i+2] for all `0 ⇐ i < F.length - 2.

Also, note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.

Return any Fibonacci-like sequence split from S, or return [] if it cannot be done.

Example 1:

Input: "123456579"
Output: [123,456,579]

Example 2:

Input: "11235813"
Output: [1,1,2,3,5,8,13]

Example 3:

Input: "112358130"
Output: []
Explanation: The task is impossible.

Example 4:

Input: "0123"
Output: []
Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.

Example 5:

Input: "1101111"
Output: [110, 1, 111]
Explanation: The output [11, 0, 11, 11] would also be accepted.

*Note: *

  • 1 ⇐ S.length ⇐ 200

  • S contains only digits.

1
Unresolved directive in 0842-split-array-into-fibonacci-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0842_SplitArrayIntoFibonacciSequence.java[]

843. Guess the Word

This problem is an interactive problem new to the LeetCode platform.

We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.

You may call master.guess(word) to guess a word. The guessed word should have type string and must be from the original list with 6 lowercase letters.

This function returns an integer type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1 instead.

For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess and at least one of these guesses was the secret, you pass the testcase.

Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list. The letters of each word in those testcases were chosen independently at random from 'a' to 'z', such that every word in the given word lists is unique.

Example 1:
Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"]

Explanation:

master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.
master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.
master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.
master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.
master.guess("abcczz") returns 4, because "abcczz" has 4 matches.

We made 5 calls to master.guess and one of them was the secret, so we pass the test case.

Note: Any solutions that attempt to circumvent the judge will result in disqualification.

1
Unresolved directive in 0843-guess-the-word.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0843_GuessTheWord.java[]

844. Backspace String Compare

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

Example 1:

Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:

Input: S = "ab#", T = "c#d"
Output: true
Explanation: Both S and T become "".

Example 3:

Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:

Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:

  • 1 ⇐ S.length ⇐ 200

  • 1 ⇐ T.length ⇐ 200

  • S and T only contain lowercase letters and '#' characters.

Follow up:

  • Can you solve it in O(N) time and O(1) space?

1
Unresolved directive in 0844-backspace-string-compare.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0844_BackspaceStringCompare.java[]

845. Longest Mountain in Array

Let’s call any (contiguous) subarray B (of A) a mountain if the following properties hold:

  • B.length >= 3

  • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < …​ B[i-1] < B[i] > B[i+1] > …​ > B[B.length - 1]

(Note that B could be any subarray of A, including the entire array A.)

Given an array A of integers, return the length of the longest mountain.

Return 0 if there is no mountain.

Example 1:

Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:

Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

Note:

  • 0 ⇐ A.length ⇐ 10000

  • 0 ⇐ A[i] ⇐ 10000

Follow up:

  • Can you solve it using only one pass?

  • Can you solve it in O(1) space?

1
Unresolved directive in 0845-longest-mountain-in-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0845_LongestMountainInArray.java[]

846. Hand of Straights

Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

Return true if and only if she can.

Example 1:

Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].

Example 2:

Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.

Note:

  1. 1 ⇐ hand.length ⇐ 10000

  2. 0 ⇐ hand[i] ⇐ 10^9

  3. 1 ⇐ W ⇐ hand.length

1
Unresolved directive in 0846-hand-of-straights.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0846_HandOfStraights.java[]

847. Shortest Path Visiting All Nodes

An undirected, connected graph of N nodes (labeled 0, 1, 2, …​, N-1) is given as graph.

graph.length = N, and j != i is in the list graph[i] exactly once, if and only if nodes i and j are connected.

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Example 1:

Input: [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]

Example 2:

Input: [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]

Note:

  1. 1 ⇐ graph.length ⇐ 12

  2. 0 ⇐ graph[i].length < graph.length

1
Unresolved directive in 0847-shortest-path-visiting-all-nodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0847_ShortestPathVisitingAllNodes.java[]

848. Shifting Letters

We have a string S of lowercase letters, and an integer array shifts.

Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').

For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.

Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times.

Return the final string after all such shifts to S are applied.

Example 1:

Input: S = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation:
We start with "abc".
After shifting the first 1 letters of S by 3, we have "dbc".
After shifting the first 2 letters of S by 5, we have "igc".
After shifting the first 3 letters of S by 9, we have "rpl", the answer.

Note:

  1. 1 ⇐ S.length = shifts.length ⇐ 20000

  2. 0 ⇐ shifts[i] ⇐ 10 ^ 9

1
Unresolved directive in 0848-shifting-letters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0848_ShiftingLetters.java[]

849. Maximize Distance to Closest Person

In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.

There is at least one empty seat, and at least one person sitting.

Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.

Return that maximum distance to closest person.

Example 1:

Input: [1,0,0,0,1,0,1]
Output: 2
Explanation:
If Alex sits in the second open seat (seats[2]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.

Example 2:

Input: [1,0,0,0]
Output: 3
Explanation:
If Alex sits in the last seat, the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.

Note:

  1. 1 ⇐ seats.length ⇐ 20000

  2. seats contains only 0s or 1s, at least one 0, and at least one 1.

1
Unresolved directive in 0849-maximize-distance-to-closest-person.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0849_MaximizeDistanceToClosestPerson.java[]

850. Rectangle Area II

We are given a list of (axis-aligned) rectangles. Each `rectangle[i] = [x1, y1, x2, y2] `, where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the `i`th rectangle.

Find the total area covered by all rectangles in the plane. Since the answer may be too large, return it modulo 10^9 + 7.

rectangle area ii pic

Example 1:

Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: As illustrated in the picture.

Example 2:

Input: [[0,0,1000000000,1000000000]]
Output: 49
Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49.

Note:

  • 1 ⇐ rectangles.length ⇐ 200

  • <font face="monospace">rectanges[i].length = 4

  • 0 ⇐ rectangles[i][j] ⇐ 10^9

  • The total area covered by all rectangles will never exceed 2^63 - 1 and thus will fit in a 64-bit signed integer.

1
Unresolved directive in 0850-rectangle-area-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0850_RectangleAreaII.java[]

851. Loud and Rich

In a group of N people (labelled 0, 1, 2, …​, N-1), each person has different amounts of money, and different levels of quietness.

For convenience, we’ll call the person with label x, simply "person `x`".

We’ll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may only be a subset of valid observations.

Also, we’ll say quiet[x] = q if person <font face="monospace">x has quietness q.

Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x.

Example 1:

Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
Output: [5,5,2,5,4,5,6,7]
Explanation:
answer[0] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet[x]) is person 7, but
it isn't clear if they have more money than person 0.

answer[7] = 7.
Among all people that definitely have equal to or more money than person 7
(which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x])
is person 7.

The other answers can be filled out with similar reasoning.

Note:

  1. 1 ⇐ quiet.length = N ⇐ 500

  2. 0 ⇐ quiet[i] < N, all quiet[i] are different.

  3. 0 ⇐ richer.length ⇐ N * (N-1) / 2

  4. 0 ⇐ richer[i][j] < N

  5. richer[i][0] != richer[i][1]

  6. `richer[i]’s are all different.

  7. The observations in richer are all logically consistent.

1
Unresolved directive in 0851-loud-and-rich.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0851_LoudAndRich.java[]

852. Peak Index in a Mountain Array

Let’s call an array A a mountain if the following properties hold:

  • A.length >= 3

  • There exists some 0 < i < A.length - 1 such that A[0] < A[1] < …​ A[i-1] < A[i] > A[i+1] > …​ > A[A.length - 1]

Given an array that is definitely a mountain, return any i such that A[0] < A[1] < …​ A[i-1] < A[i] > A[i+1] > …​ > A[A.length - 1].

Example 1:

Input: [0,1,0]
Output: 1

Example 2:

Input: [0,2,1,0]
Output: 1

Note:

  • 3 ⇐ A.length ⇐ 10000

  • <font face="monospace">0 ⇐ A[i] ⇐ 10^6

  • A is a mountain, as defined above.

1
Unresolved directive in 0852-peak-index-in-a-mountain-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0852_PeakIndexInAMountainArray.java[]

853. Car Fleet

N cars are going to the same destination along a one lane road. The destination is target miles away.

Each car i has a constant speed speed[i] (in miles per hour), and initial position position[i] miles towards the target along the road.

A car can never pass another car ahead of it, but it can catch up to it, and drive bumper to bumper at the same speed.

The distance between these two cars is ignored - they are assumed to have the same position.

A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.

If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.

How many car fleets will arrive at the destination?

Example 1:

Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3
Explanation:
The cars starting at 10 and 8 become a fleet, meeting each other at 12.
The car starting at 0 doesn't catch up to any other car, so it is a fleet by itself.
The cars starting at 5 and 3 become a fleet, meeting each other at 6.
Note that no other cars meet these fleets before the destination, so the answer is 3.

Note:

  1. 0 ⇐ N ⇐ 10 ^ 4

  2. 0 < target ⇐ 10 ^ 6

  3. 0 < speed[i] ⇐ 10 ^ 6

  4. 0 ⇐ position[i] < target

  5. All initial positions are different.

1
Unresolved directive in 0853-car-fleet.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0853_CarFleet.java[]

854. K-Similar Strings

Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.

Given two anagrams A and B, return the smallest K for which A and B are K-similar.

Example 1:

Input: A = "ab", B = "ba"
Output: 1

Example 2:

Input: A = "abc", B = "bca"
Output: 2

Example 3:

Input: A = "abac", B = "baca"
Output: 2

Example 4:

Input: A = "aabc", B = "abca"
Output: 2

Note:

  1. 1 ⇐ A.length == B.length ⇐ 20

  2. A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}

1
Unresolved directive in 0854-k-similar-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0854_KSimilarStrings.java[]

855. Exam Room

In an exam room, there are N seats in a single row, numbered 0, 1, 2, …​, N-1.

When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. (Also, if no one is in the room, then the student sits at seat number 0.)

Return a class ExamRoom(int N) that exposes two functions: ExamRoom.seat() returning an int representing what seat the student sat in, and ExamRoom.leave(int p) representing that the student in seat number p now leaves the room. It is guaranteed that any calls to ExamRoom.leave(p) have a student sitting in seat p.

Example 1:

Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
Output: [null,0,9,4,2,null,5]
Explanation:
ExamRoom(10) -> null
seat() -> 0, no one is in the room, then the student sits at seat number 0.
seat() -> 9, the student sits at the last seat number 9.
seat() -> 4, the student sits at the last seat number 4.
seat() -> 2, the student sits at the last seat number 2.
leave(4) -> null
seat() -> 5, the student sits at the last seat number 5.

​​​​​​​

Note:

  1. 1 ⇐ N ⇐ 10^9

  2. ExamRoom.seat() and ExamRoom.leave() will be called at most 10^4 times across all test cases.

  3. Calls to ExamRoom.leave(p) are guaranteed to have a student currently sitting in seat number p.

1
Unresolved directive in 0855-exam-room.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0855_ExamRoom.java[]

856. Score of Parentheses

Given a balanced parentheses string S, compute the score of the string based on the following rule:

  • () has score 1

  • AB has score A + B, where A and B are balanced parentheses strings.

  • (A) has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: "()"
Output: 1

Example 2:

Input: "(())"
Output: 2

Example 3:

Input: "()()"
Output: 2

Example 4:

Input: ")(()"
Output: 6

Note:

  • S is a balanced parentheses string, containing only ( and ).

  • 2 ⇐ S.length ⇐ 50

1
Unresolved directive in 0856-score-of-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0856_ScoreOfParentheses.java[]

857. Minimum Cost to Hire K Workers

There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].

Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:

  1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.

  2. Every worker in the paid group must be paid at least their minimum wage expectation.

Return the least amount of money needed to form a paid group satisfying the above conditions.

Example 1:

Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.

Example 2:

Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.

Note:

  1. 1 ⇐ K ⇐ N ⇐ 10000, where N = quality.length = wage.length

  2. 1 ⇐ quality[i] ⇐ 10000

  3. 1 ⇐ wage[i] ⇐ 10000

  4. Answers within 10^-5 of the correct answer will be considered correct.

1
Unresolved directive in 0857-minimum-cost-to-hire-k-workers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0857_MinimumCostToHireKWorkers.java[]

858. Mirror Reflection

There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the `0`th receptor.

Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)

Example 1:

Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/18/reflection.png" alt="reflection">

Note:

  1. 1 ⇐ p ⇐ 1000

  2. 0 ⇐ q ⇐ p

1
Unresolved directive in 0858-mirror-reflection.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0858_MirrorReflection.java[]

859. Buddy Strings

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

Example 1:

Input: A = "ab", B = "ba"
Output: true

Example 2:

Input: A = "ab", B = "ab"
Output: false

Example 3:

Input: A = "aa", B = "aa"
Output: true

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false

Note:

  1. 0 ⇐ A.length ⇐ 20000

  2. 0 ⇐ B.length ⇐ 20000

  3. A and B consist only of lowercase letters.

1
Unresolved directive in 0859-buddy-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0859_BuddyStrings.java[]

860. Lemonade Change

At a lemonade stand, each lemonade costs $5.

Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills).

Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.

Note that you don’t have any change in hand at first.

Return true if and only if you can provide every customer with correct change.

Example 1:

Input: [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.

Example 2:

Input: [5,5,10]
Output: true

Example 3:

Input: [10,10]
Output: false

Example 4:

Input: [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can't give change of $15 back because we only have two $10 bills.
Since not every customer received correct change, the answer is false.

Note:

  • 0 ⇐ bills.length ⇐ 10000

  • bills[i] will be either 5, 10, or 20.

1
Unresolved directive in 0860-lemonade-change.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0860_LemonadeChange.java[]

861. Score After Flipping Matrix

We have a two dimensional matrix A where each value is 0 or 1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all `0`s to `1`s, and all `1`s to `0`s.

After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

Return the highest possible score.

Example 1:

Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Note:

  1. 1 ⇐ A.length ⇐ 20

  2. 1 ⇐ A[0].length ⇐ 20

  3. A[i][j] is 0 or 1.

1
Unresolved directive in 0861-score-after-flipping-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0861_ScoreAfterFlippingMatrix.java[]

862. Shortest Subarray with Sum at Least K

Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K.

If there is no non-empty subarray with sum at least K, return -1.

Example 1:

Input: A = [1], K = 1
Output: 1

Example 2:

Input: A = [1,2], K = 4
Output: -1

Example 3:

Input: A = [2,-1,2], K = 3
Output: 3

Note:

  1. 1 ⇐ A.length ⇐ 50000

  2. -10 ^ 5 ⇐ A[i] ⇐ 10 ^ 5

  3. 1 ⇐ K ⇐ 10 ^ 9

1
Unresolved directive in 0862-shortest-subarray-with-sum-at-least-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0862_ShortestSubarrayWithSumAtLeastK.java[]

863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2

Output: [7,4,1]

Explanation:
The nodes that are a distance 2 from the target node (with value 5)
have values 7, 4, and 1.

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png" alt="sketch0">

Note that the inputs "root" and "target" are actually TreeNodes.
The descriptions of the inputs above are just serializations of these objects.

Note:

  1. The given tree is non-empty.

  2. Each node in the tree has unique values 0 ⇐ node.val ⇐ 500.

  3. The target node is a node in the tree.

  4. 0 ⇐ K ⇐ 1000.

1
Unresolved directive in 0863-all-nodes-distance-k-in-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0863_AllNodesDistanceKInBinaryTree.java[]

864. Shortest Path to Get All Keys

We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", …​) are keys, and ("A", "B", …​) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can’t walk over a lock unless we have the corresponding key.

For some <font face="monospace">1 ⇐ K ⇐ 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it’s impossible, return -1.

Example 1:

Input: ["@.a.","#.","b.A.B"]
Output: 8

Example 2:

Input: ["@..aA","..B#.","....b"]
Output: 6

Note:

  1. 1 ⇐ grid.length ⇐ 30

  2. 1 ⇐ grid[0].length ⇐ 30

  3. grid[i][j] contains only` '.‘, '#', '@', 'a'-`’f’` and 'A'-'F'

  4. The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.

1
Unresolved directive in 0864-shortest-path-to-get-all-keys.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0864_ShortestPathToGetAllKeys.java[]

865. Smallest Subtree with all the Deepest Nodes

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

Example 1:

Input: [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation:

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" alt="sketch1">

We return the node with value 2, colored in yellow in the diagram.
The nodes colored in blue are the deepest nodes of the tree.
The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree.
The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2.
Both the input and output have TreeNode type.

Note:

  • The number of nodes in the tree will be between 1 and 500.

  • The values of each node are unique.

1
Unresolved directive in 0865-smallest-subtree-with-all-the-deepest-nodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0865_SmallestSubtreeWithAllTheDeepestNodes.java[]

866. Prime Palindrome

Find the smallest prime palindrome greater than or equal to N.

Recall that a number is prime if it’s only divisors are 1 and itself, and it is greater than 1.

For example, 2,3,5,7,11 and 13 are primes.

Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.

For example, 12321 is a palindrome.

Example 1:

Input: 6
Output: 7

Example 2:

Input: 8
Output: 11

Example 3:

Input: 13
Output: 101

Note:

  • 1 ⇐ N ⇐ 10^8

  • The answer is guaranteed to exist and be less than 2 * 10^8.

1
Unresolved directive in 0866-prime-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0866_PrimePalindrome.java[]

867. Transpose Matrix

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it’s main diagonal, switching the row and column indices of the matrix.

hint transpose

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]

Note:

  1. 1 ⇐ A.length ⇐ 1000

  2. 1 ⇐ A[0].length ⇐ 1000

1
Unresolved directive in 0867-transpose-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0867_TransposeMatrix.java[]

868. Binary Gap

Given a positive integer N, find and return the longest distance between two consecutive 1’s in the binary representation of N.

If there aren’t two consecutive 1’s, return <font face="monospace">0.

Example 1:

Input: 22
Output: 2
Explanation:
22 in binary is 0b10110.
In the binary representation of 22, there are three ones, and two consecutive pairs of 1's.
The first consecutive pair of 1's have distance 2.
The second consecutive pair of 1's have distance 1.
The answer is the largest of these two distances, which is 2.

Example 2:

Input: 5
Output: 2
Explanation:
5 in binary is 0b101.

Example 3:

Input: 6
Output: 1
Explanation:
6 in binary is 0b110.

Example 4:

Input: 8
Output: 0
Explanation:
8 in binary is 0b1000.
There aren't any consecutive pairs of 1's in the binary representation of 8, so we return 0.

Note:

  • 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 0868-binary-gap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0868_BinaryGap.java[]

869. Reordered Power of 2

Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.

Return true if and only if we can do this in a way such that the resulting number is a power of 2.

Example 1:

Input: 1
Output: true

Example 2:

Input: 10
Output: false

Example 3:

Input: 16
Output: true

Example 4:

Input: 24
Output: false

Example 5:

Input: 46
Output: true

Note:

  1. 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 0869-reordered-power-of-2.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0869_ReorderedPowerOf2.java[]

870. Advantage Shuffle

Given two arrays A and B of equal size, the advantage of A with respect to B` is the number of indices `i for which A[i] > B[i].

Return any permutation of A that maximizes its advantage with respect to B.

Example 1:

Input: A = [2,7,11,15], B = [1,10,4,11]
Output: [2,11,7,15]

Example 2:

Input: A = [12,24,8,32], B = [13,25,32,11]
Output: [24,32,8,12]

Note:

  1. 1 ⇐ A.length = B.length ⇐ 10000

  2. 0 ⇐ A[i] ⇐ 10^9

  3. 0 ⇐ B[i] ⇐ 10^9

1
Unresolved directive in 0870-advantage-shuffle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0870_AdvantageShuffle.java[]

871. Minimum Number of Refueling Stops

A car travels from a starting position to a destination which is target miles east of the starting position.

Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses 1 liter of gas per 1 mile that it drives.

When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

What is the least number of refueling stops the car must make in order to reach its destination? If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

Example 1:

Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.

Example 2:

Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).

Example 3:

Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation:
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

Note:

  1. 1 ⇐ target, startFuel, stations[i][1] ⇐ 10^9

  2. 0 ⇐ stations.length ⇐ 500

  3. 0 < stations[0][0] < stations[1][0] < …​ < stations[stations.length-1][0] < target

1
Unresolved directive in 0871-minimum-number-of-refueling-stops.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0871_MinimumNumberOfRefuelingStops.java[]

872. Leaf-Similar Trees

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

tree

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

  • Both of the given trees will have between 1 and 100 nodes.

1
Unresolved directive in 0872-leaf-similar-trees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0872_LeafSimilarTrees.java[]

873. Length of Longest Fibonacci Subsequence

A sequence X_1, X_2, …​, X_n is fibonacci-like if:

  • n >= 3

  • X_i + X_{i+1} = X_{i+2} for all i + 2 ⇐ n

Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.

(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)

Example 1:

Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].

Example 2:

Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].

Note:

  • 3 ⇐ A.length ⇐ 1000

  • 1 ⇐ A[0] < A[1] < …​ < A[A.length - 1] ⇐ 10^9

  • (The time limit has been reduced by 50% for submissions in Java, C, and C++.)

1
Unresolved directive in 0873-length-of-longest-fibonacci-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0873_LengthOfLongestFibonacciSubsequence.java[]

874. Walking Robot Simulation

A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:

  • -2: turn left 90 degrees

  • -1: turn right 90 degrees

  • 1 ⇐ x ⇐ 9: move forward x units

Some of the grid squares are obstacles.

The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])

If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)

Return the square of the maximum Euclidean distance that the robot will be from the origin.

Example 1:

Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)

Example 2:

Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)

Note:

  • 0 ⇐ commands.length ⇐ 10000

  • 0 ⇐ obstacles.length ⇐ 10000

  • -30000 ⇐ obstacle[i][0] ⇐ 30000

  • -30000 ⇐ obstacle[i][1] ⇐ 30000

  • The answer is guaranteed to be less than 2 ^ 31.

1
Unresolved directive in 0874-walking-robot-simulation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0874_WalkingRobotSimulation.java[]

875. Koko Eating Bananas

Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in H hours.

Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K bananas, she eats all of them instead, and won’t eat any more bananas during this hour.

Koko likes to eat slowly, but still wants to finish eating all the bananas before the guards come back.

Return the minimum integer K such that she can eat all the bananas within H hours.

Example 1:

Input: piles = [3,6,7,11], H = 8
Output: 4

Example 2:

Input: piles = [30,11,23,4,20], H = 5
Output: 30

Example 3:

Input: piles = [30,11,23,4,20], H = 6
Output: 23

Note:

  • 1 ⇐ piles.length ⇐ 10^4

  • piles.length ⇐ H ⇐ 10^9

  • 1 ⇐ piles[i] ⇐ 10^9

1
Unresolved directive in 0875-koko-eating-bananas.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0875_KokoEatingBananas.java[]

876. Middle of the Linked List

Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3.  (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:

Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:

  • The number of nodes in the given list will be between 1 and 100.

1
Unresolved directive in 0876-middle-of-the-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0876_MiddleOfTheLinkedList.java[]

877. Stone Game

Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.

Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

Example 1:

Input: [5,3,4,5]
Output: true
Explanation:
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.

Note:

  1. 2 ⇐ piles.length ⇐ 500

  2. piles.length is even.

  3. 1 ⇐ piles[i] ⇐ 500

  4. sum(piles) is odd.

1
Unresolved directive in 0877-stone-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0877_StoneGame.java[]

878. Nth Magical Number

A positive integer is magical if it is divisible by either <font face="monospace">A or <font face="monospace">B.

Return the <font face="monospace">N-th magical number. Since the answer may be very large, *return it modulo *10^9 + 7.

Example 1:

Input: N = 1, A = 2, B = 3
Output: 2

Example 2:

Input: N = 4, A = 2, B = 3
Output: 6

Example 3:

Input: N = 5, A = 2, B = 4
Output: 10

Example 4:

Input: N = 3, A = 6, B = 4
Output: 8

Note:

  1. 1 ⇐ N ⇐ 10^9

  2. 2 ⇐ A ⇐ 40000

  3. 2 ⇐ B ⇐ 40000

1
Unresolved directive in 0878-nth-magical-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0878_NthMagicalNumber.java[]

879. Profitable Schemes

There are G people in a gang, and a list of various crimes they could commit.

The i-th crime generates a profit[i] and requires group[i] gang members to participate.

If a gang member participates in one crime, that member can’t participate in another crime.

Let’s call a profitable scheme any subset of these crimes that generates at least P profit, and the total number of gang members participating in that subset of crimes is at most G.

How many schemes can be chosen? Since the answer may be very large, return it modulo 10^9 + 7.

Example 1:

Input: G = 5, P = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation:
To make a profit of at least 3, the gang could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.

Example 2:

Input: G = 10, P = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation:
To make a profit of at least 5, the gang could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).

Note:

  1. 1 ⇐ G ⇐ 100

  2. 0 ⇐ P ⇐ 100

  3. 1 ⇐ group[i] ⇐ 100

  4. 0 ⇐ profit[i] ⇐ 100

  5. 1 ⇐ group.length = profit.length ⇐ 100

1
Unresolved directive in 0879-profitable-schemes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0879_ProfitableSchemes.java[]

880. Decoded String at Index

An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:

  • If the character read is a letter, that letter is written onto the tape.

  • If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total.

Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string.

Example 1:

Input: S = "leet2code3", K = 10
Output: "o"
Explanation:
The decoded string is "leetleetcodeleetleetcodeleetleetcode".
The 10th letter in the string is "o".

Example 2:

Input: S = "ha22", K = 5
Output: "h"
Explanation:
The decoded string is "hahahaha".  The 5th letter is "h".

Example 3:

Input: S = "a2345678999999999999999", K = 1
Output: "a"
Explanation:
The decoded string is "a" repeated 8301530446056247680 times.  The 1st letter is "a".

Note:

  • 2 ⇐ S.length ⇐ 100

  • S will only contain lowercase letters and digits 2 through 9.

  • S starts with a letter.

  • 1 ⇐ K ⇐ 10^9

  • The decoded string is guaranteed to have less than 2^63 letters.

1
Unresolved directive in 0880-decoded-string-at-index.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0880_DecodedStringAtIndex.java[]

881. Boats to Save People

The i-th person has weight people[i], and each boat can carry a maximum weight of limit.

Each boat carries at most 2 people at the same time, provided the sum of the weight of those people is at most limit.

Return the minimum number of boats to carry every given person. (It is guaranteed each person can be carried by a boat.)

Example 1:

Input: people = [1,2], limit = 3
Output: 1
Explanation: 1 boat (1, 2)

Example 2:

Input: people = [3,2,2,1], limit = 3
Output: 3
Explanation: 3 boats (1, 2), (2) and (3)

Example 3:

Input: people = [3,5,3,4], limit = 5
Output: 4
Explanation: 4 boats (3), (3), (4), (5)

Note:

  • 1 ⇐ people.length ⇐ 50000

  • 1 ⇐ people[i] ⇐ limit ⇐ 30000

1
Unresolved directive in 0881-boats-to-save-people.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0881_BoatsToSavePeople.java[]

882. Reachable Nodes In Subdivided Graph

Starting with an undirected graph (the "original graph") with nodes from 0 to N-1, subdivisions are made to some of the edges.

The graph is given as follows: edges[k] is a list of integer pairs (i, j, n) such that (i, j) is an edge of the original graph,

and n is the total number of new nodes on that edge.

Then, the edge (i, j) is deleted from the original graph, n new nodes (x_1, x_2, …​, x_n) are added to the original graph,

and n+1 new edges (i, x_1), (x_1, x_2), (x_2, x_3), …​, (x_{n-1}, x_n), (x_n, j) are added to the original graph.

Now, you start at node 0 from the original graph, and in each move, you travel along one edge.

Return how many nodes you can reach in at most M moves.

Example 1:

Input: edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3
Output: 13
Explanation:
The nodes that are reachable in the final graph after M = 6 moves are indicated below.

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/01/origfinal.png" alt="origfinal">

Example 2:

Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4
Output: 23

Note:

  1. 0 ⇐ edges.length ⇐ 10000

  2. 0 ⇐ edges[i][0] < edges[i][1] < N

  3. There does not exist any i != j for which edges[i][0] == edges[j][0] and edges[i][1] == edges[j][1].

  4. The original graph has no parallel edges.

  5. 0 ⇐ edges[i][2] ⇐ 10000

  6. 0 ⇐ M ⇐ 10^9

  7. <font face="monospace">1 ⇐ N ⇐ 3000

  8. A reachable node is a node that can be travelled to using at most M moves starting from node 0.

1
Unresolved directive in 0882-reachable-nodes-in-subdivided-graph.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0882_ReachableNodesInSubdividedGraph.java[]

883. Projection Area of 3D Shapes

On a N * N grid, we place some `1 * 1 * 1 `cubes that are axis-aligned with the x, y, and z axes.

Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).

Now we view the projection of these cubes onto the xy, yz, and zx planes.

A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.

Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side.

Return the total area of all three projections.

Example 1:

Input: [[2]]
Output: 5

Example 2:

Input: [[1,2],[3,4]]
Output: 17
Explanation:
Here are the three projections ("shadows") of the shape made with each axis-aligned plane.

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/02/shadow.png" alt="shadow">

Example 3:

Input: [[1,0],[0,2]]
Output: 8

Example 4:

Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 14

Example 5:

Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 21

Note:

  • 1 ⇐ grid.length = grid[0].length ⇐ 50

  • 0 ⇐ grid[i][j] ⇐ 50

1
Unresolved directive in 0883-projection-area-of-3d-shapes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0883_ProjectionAreaOf3DShapes.java[]

884. Uncommon Words from Two Sentences

We are given two sentences A and B. (A sentence is a string of space separated words. Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words.

You may return the list in any order.

Example 1:

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]

Example 2:

Input: A = "apple apple", B = "banana"
Output: ["banana"]

Note:

  1. 0 ⇐ A.length ⇐ 200

  2. 0 ⇐ B.length ⇐ 200

  3. A and B both contain only spaces and lowercase letters.

1
Unresolved directive in 0884-uncommon-words-from-two-sentences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0884_UncommonWordsFromTwoSentences.java[]

885. Spiral Matrix III

On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east.

Here, the north-west corner of the grid is at the first row and column, and the south-east corner of the grid is at the last row and column.

Now, we walk in a clockwise spiral shape to visit every position in this grid.

Whenever we would move outside the boundary of the grid, we continue our walk outside the grid (but may return to the grid boundary later.)

Eventually, we reach all R * C spaces of the grid.

Return a list of coordinates representing the positions of the grid in the order they were visited.

Example 1:

Input: R = 1, C = 4, r0 = 0, c0 = 0
Output: [[0,0],[0,1],[0,2],[0,3]]

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_1.png" alt="example 1">

Example 2:

Input: R = 5, C = 6, r0 = 1, c0 = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/24/example_2.png" alt="example 2">

Note:

  1. 1 ⇐ R ⇐ 100

  2. 1 ⇐ C ⇐ 100

  3. 0 ⇐ r0 < R

  4. 0 ⇐ c0 < C

1
Unresolved directive in 0885-spiral-matrix-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0885_SpiralMatrixIII.java[]

886. Possible Bipartition

Given a set of N people (numbered 1, 2, …​, N), we would like to split everyone into two groups of any size.

Each person may dislike some other people, and they should not go into the same group.

Formally, if dislikes[i] = [a, b], it means it is not allowed to put the people numbered a and b into the same group.

Return true if and only if it is possible to split everyone into two groups in this way.

Example 1:

Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
Output: true
Explanation: group1 [1,4], group2 [2,3]

Example 2:

Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false

Example 3:

Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
Output: false

Note:

  1. 1 ⇐ N ⇐ 2000

  2. 0 ⇐ dislikes.length ⇐ 10000

  3. 1 ⇐ dislikes[i][j] ⇐ N

  4. dislikes[i][0] < dislikes[i][1]

  5. There does not exist i != j for which dislikes[i] == dislikes[j].

1
Unresolved directive in 0886-possible-bipartition.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0886_PossibleBipartition.java[]

887. Super Egg Drop

You are given K eggs, and you have access to a building with N floors from 1 to N.

Each egg is identical in function, and if an egg breaks, you cannot drop it again.

You know that there exists a floor F with 0 ⇐ F ⇐ N such that any egg dropped at a floor higher than F will break, and any egg dropped at or below floor F will not break.

Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 ⇐ X ⇐ N).

Your goal is to know with certainty what the value of F is.

What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F?

Example 1:

Input: K = 1, N = 2
Output: 2
Explanation:
Drop the egg from floor 1.  If it breaks, we know with certainty that F = 0.
Otherwise, drop the egg from floor 2.  If it breaks, we know with certainty that F = 1.
If it didn't break, then we know with certainty F = 2.
Hence, we needed 2 moves in the worst case to know what F is with certainty.

Example 2:

Input: K = 2, N = 6
Output: 3

Example 3:

Input: K = 3, N = 14
Output: 4

Note:

  1. 1 ⇐ K ⇐ 100

  2. 1 ⇐ N ⇐ 10000

1
Unresolved directive in 0887-super-egg-drop.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0887_SuperEggDrop.java[]

888. Fair Candy Swap

Alice and Bob have candy bars of different sizes: A[i] is the size of the i-th bar of candy that Alice has, and B[j] is the size of the j-th bar of candy that Bob has.

Since they are friends, they would like to exchange one candy bar each so that after the exchange, they both have the same total amount of candy. (The total amount of candy a person has is the sum of the sizes of candy bars they have.)

Return an integer array ans where ans[0] is the size of the candy bar that Alice must exchange, and ans[1] is the size of the candy bar that Bob must exchange.

If there are multiple answers, you may return any one of them. It is guaranteed an answer exists.

Example 1:

Input: A = [1,1], B = [2,2]
Output: [1,2]

Example 2:

Input: A = [1,2], B = [2,3]
Output: [1,2]

Example 3:

Input: A = [2], B = [1,3]
Output: [2,3]

Example 4:

Input: A = [1,2,5], B = [2,4]
Output: [5,4]

Note:

  • 1 ⇐ A.length ⇐ 10000

  • 1 ⇐ B.length ⇐ 10000

  • 1 ⇐ A[i] ⇐ 100000

  • 1 ⇐ B[i] ⇐ 100000

  • It is guaranteed that Alice and Bob have different total amounts of candy.

  • It is guaranteed there exists an answer.

1
Unresolved directive in 0888-fair-candy-swap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0888_FairCandySwap.java[]

889. Construct Binary Tree from Preorder and Postorder Traversal

Return any binary tree that matches the given preorder and postorder traversals.

Values in the traversals pre and post are distinct positive integers.

Example 1:

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]

Note:

  • 1 ⇐ pre.length == post.length ⇐ 30

  • pre[] and post[] are both permutations of 1, 2, …​, pre.length.

  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

1
Unresolved directive in 0889-construct-binary-tree-from-preorder-and-postorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0889_ConstructBinaryTreeFromPreorderAndPostorderTraversal.java[]

890. Find and Replace Pattern

You have a list of words and a pattern, and you want to know which words in words matches the pattern.

A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.

(Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.)

Return a list of the words in words that match the given pattern.

You may return the answer in any order.

Example 1:

Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation,
since a and b map to the same letter.

Note:

  • 1 ⇐ words.length ⇐ 50

  • 1 ⇐ pattern.length = words[i].length ⇐ 20

1
Unresolved directive in 0890-find-and-replace-pattern.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0890_FindAndReplacePattern.java[]

891. Sum of Subsequence Widths

Given an array of integers A, consider all non-empty subsequences of A.

For any sequence S, let the width of S be the difference between the maximum and minimum element of S.

Return the sum of the widths of all subsequences of A.

As the answer may be very large, return the answer modulo 10^9 + 7.

Example 1:

Input: [2,1,3]
Output: 6
Explanation:
Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

Note:

  • 1 ⇐ A.length ⇐ 20000

  • 1 ⇐ A[i] ⇐ 20000

1
Unresolved directive in 0891-sum-of-subsequence-widths.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0891_SumOfSubsequenceWidths.java[]

892. Surface Area of 3D Shapes

On a N * N grid, we place some `1 * 1 * 1 `cubes.

Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).

Return the total surface area of the resulting shapes.

Example 1:

Input: [[2]]
Output: 10

Example 2:

Input: [[1,2],[3,4]]
Output: 34

Example 3:

Input: [[1,0],[0,2]]
Output: 16

Example 4:

Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 32

Example 5:

Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 46

Note:

  • 1 ⇐ N ⇐ 50

  • 0 ⇐ grid[i][j] ⇐ 50

1
Unresolved directive in 0892-surface-area-of-3d-shapes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0892_SurfaceAreaOf3DShapes.java[]

893. Groups of Special-Equivalent Strings

You are given an array A of strings.

A move onto S` consists of swapping any two even indexed characters of `S, or any two odd indexed characters of S.

Two strings S and T are special-equivalent if after any number of moves onto S`, `S == T.

For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make the moves "zzxy" → "xzzy" → "xyzz" that swap S[0] and S[2], then S[1] and S[3].

Now, a group of special-equivalent strings from `A` is a non-empty subset of A such that:

  • Every pair of strings in the group are special equivalent, and;

  • The group is the largest size possible (ie., there isn’t a string S not in the group such that S is special equivalent to every string in the group)

Return the number of groups of special-equivalent strings from A.

Example 1:

Input: ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]
Output: 3
Explanation:
One group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings are all pairwise special equivalent to these.

The other two groups are ["xyzz", "zzxy"] and ["zzyx"].  Note that in particular, "zzxy" is not special equivalent to "zzyx".

Example 2:

Input: ["abc","acb","bac","bca","cab","cba"]
Output: 3

Note:

  • 1 ⇐ A.length ⇐ 1000

  • 1 ⇐ A[i].length ⇐ 20

  • All A[i] have the same length.

  • All A[i] consist of only lowercase letters.

1
Unresolved directive in 0893-groups-of-special-equivalent-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0893_GroupsOfSpecialEquivalentStrings.java[]

894. All Possible Full Binary Trees

A full binary tree is a binary tree where each node has exactly 0 or 2 children.

Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.

Each node of each tree in the answer must have node.val = 0.

You may return the final list of trees in any order.

Example 1:

Input: 7
Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
Explanation:

:https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" alt="fivetrees">

Note:

  • 1 ⇐ N ⇐ 20

1
Unresolved directive in 0894-all-possible-full-binary-trees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0894_AllPossibleFullBinaryTrees.java[]

895. Maximum Frequency Stack

Implement FreqStack, a class which simulates the operation of a stack-like data structure.

FreqStack has two functions:

  • push(int x), which pushes an integer x onto the stack.

  • pop(), which removes and returns the most frequent element in the stack.

  • If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.

Example 1:

Input:
 ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],
 [[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
Output: [null,null,null,null,null,null,null,5,7,5,4]
Explanation:
After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top.  Then:

pop() -> returns 5, as 5 is the most frequent.
The stack becomes [5,7,5,7,4].

pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.
The stack becomes [5,7,5,4].

pop() -> returns 5.
The stack becomes [5,7,4].

pop() -> returns 4.
The stack becomes [5,7].

Note:

  • Calls to FreqStack.push(int x) will be such that 0 ⇐ x ⇐ 10^9.

  • It is guaranteed that FreqStack.pop() won’t be called if the stack has zero elements.

  • The total number of FreqStack.push calls will not exceed 10000 in a single test case.

  • The total number of FreqStack.pop calls will not exceed 10000 in a single test case.

  • The total number of FreqStack.push and FreqStack.pop calls will not exceed 150000 across all test cases.

1
Unresolved directive in 0895-maximum-frequency-stack.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0895_MaximumFrequencyStack.java[]

896. Monotonic Array

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array A is monotone increasing if for all i ⇐ j, A[i] ⇐ A[j]. An array A is monotone decreasing if for all i ⇐ j, A[i] >= A[j].

Return true if and only if the given array A is monotonic.

Example 1:

Input: [1,2,2,3]
Output: true

Example 2:

Input: [6,5,4,4]
Output: true

Example 3:

Input: [1,3,2]
Output: false

Example 4:

Input: [1,2,4,5]
Output: true

Example 5:

Input: [1,1,1]
Output: true

Note:

  1. 1 ⇐ A.length ⇐ 50000

  2. -100000 ⇐ A[i] ⇐ 100000

1
Unresolved directive in 0896-monotonic-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0896_MonotonicArray.java[]

897. Increasing Order Search Tree

Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]

       5
      / \
    3    6
   / \    \
  2   4    8
 /        / \
1        7   9

Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
            \
             7
              \
               8
                \
                 9

Note:

  1. The number of nodes in the given tree will be between 1 and 100.

  2. Each node will have a unique integer value from 0 to 1000.

1
Unresolved directive in 0897-increasing-order-search-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0897_IncreasingOrderSearchTree.java[]

898. Bitwise ORs of Subarrays

We have an array A of non-negative integers.

For every (contiguous) subarray B = [A[i], A[i+1], …​, A[j]] (with i ⇐ j), we take the bitwise OR of all the elements in B, obtaining a result <font face="monospace">`A[i] | A[i+1] | …​ | A[j]`.

Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)

Example 1:

Input: [0]
Output: 1
Explanation:
There is only one possible result: 0.

Example 2:

Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.

Example 3:

Input: [1,2,4]
Output: 6
Explanation:
The possible results are 1, 2, 3, 4, 6, and 7.

Note:

  1. 1 ⇐ A.length ⇐ 50000

  2. 0 ⇐ A[i] ⇐ 10^9

1
Unresolved directive in 0898-bitwise-ors-of-subarrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0898_BitwiseORsOfSubarrays.java[]

899. Orderly Queue

A string S of lowercase letters is given. Then, we may make any number of moves.

In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.

Return the lexicographically smallest string we could have after any number of moves.

Example 1:

Input: S = "cba", K = 1
Output: "acb"
Explanation:
In the first move, we move the 1st character ("c") to the end, obtaining the string "bac".
In the second move, we move the 1st character ("b") to the end, obtaining the final result "acb".

Example 2:

Input: S = "baaca", K = 3
Output: "aaabc"
Explanation:
In the first move, we move the 1st character ("b") to the end, obtaining the string "aacab".
In the second move, we move the 3rd character ("c") to the end, obtaining the final result "aaabc".

Note:

  1. 1 ⇐ K ⇐ S.length ⇐ 1000

  2. S consists of lowercase letters only.

1
Unresolved directive in 0899-orderly-queue.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0899_OrderlyQueue.java[]

900. RLE Iterator

Write an iterator that iterates through a run-length encoded sequence.

The iterator is initialized by RLEIterator(int[] A), where A is a run-length encoding of some sequence. More specifically, for all even i, A[i] tells us the number of times that the non-negative integer value A[i+1] is repeated in the sequence.

The iterator supports one function: next(int n), which exhausts the next n elements (n >= 1) and returns the last element exhausted in this way. If there is no element left to exhaust, next returns -1 instead.

For example, we start with A = [3,8,0,9,2,5], which is a run-length encoding of the sequence [8,8,8,5,5]. This is because the sequence can be read as "three eights, zero nines, two fives".

Example 1:

Input: ["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]]
Output: [null,8,8,5,-1]
Explanation:
RLEIterator is initialized with RLEIterator([3,8,0,9,2,5]).
This maps to the sequence [8,8,8,5,5].
RLEIterator.next is then called 4 times:

.next(2) exhausts 2 terms of the sequence, returning 8.  The remaining sequence is now [8, 5, 5].

.next(1) exhausts 1 term of the sequence, returning 8.  The remaining sequence is now [5, 5].

.next(1) exhausts 1 term of the sequence, returning 5.  The remaining sequence is now [5].

.next(2) exhausts 2 terms, returning -1.  This is because the first term exhausted was 5,
but the second term did not exist.  Since the last term exhausted does not exist, we return -1.

Note:

  1. 0 ⇐ A.length ⇐ 1000

  2. A.length is an even integer.

  3. 0 ⇐ A[i] ⇐ 10^9

  4. There are at most 1000 calls to RLEIterator.next(int n) per test case.

  5. Each call to RLEIterator.next(int n) will have 1 ⇐ n ⇐ 10^9.

1
Unresolved directive in 0900-rle-iterator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0900_RLEIterator.java[]

901. Online Stock Span

Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock’s price for the current day.

The span of the stock’s price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.

For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

Example 1:

Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
Explanation:
First, S = StockSpanner() is initialized.  Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.

Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.

Note:

  1. Calls to StockSpanner.next(int price) will have 1 ⇐ price ⇐ 10^5.

  2. There will be at most 10000 calls to StockSpanner.next per test case.

  3. There will be at most 150000 calls to StockSpanner.next across all test cases.

  4. The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.

1
Unresolved directive in 0901-online-stock-span.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0901_OnlineStockSpan.java[]

902. Numbers At Most N Given Digit Set

We have a sorted set of digits D, a non-empty subset of {'1','2','3','4','5','6','7','8','9'}. (Note that '0' is not included.)

Now, we write numbers using these digits, using each digit as many times as we want. For example, if D = {'1','3','5'}, we may write numbers such as '13', '551', '1351315'.

Return the number of positive integers that can be written (using the digits of D) that are less than or equal to N.

Example 1:

Input: D = ["1","3","5","7"], N = 100
Output: 20
Explanation:
The 20 numbers that can be written are:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.

Example 2:

Input: D = ["1","4","9"], N = 1000000000
Output: 29523
Explanation:
We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,
81 four digit numbers, 243 five digit numbers, 729 six digit numbers,
2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.
In total, this is 29523 integers that can be written using the digits of D.

Note:

  1. D is a subset of digits '1'-'9' in sorted order.

  2. 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 0902-numbers-at-most-n-given-digit-set.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0902_NumbersAtMostNGivenDigitSet.java[]

903. Valid Permutations for DI Sequence

We are given S, a length n string of characters from the set {'D', 'I'}. (These letters stand for "decreasing" and "increasing".)

A valid permutation is a permutation P[0], P[1], …​, P[n] of integers {0, 1, …​, n}, such that for all i:

  • If S[i] == 'D', then P[i] > P[i+1], and;

  • If S[i] == 'I', then P[i] < P[i+1].

How many valid permutations are there? Since the answer may be large, return your answer modulo 10^9 + 7.

Example 1:

Input: "DID"
Output: 5
Explanation:
The 5 valid permutations of (0, 1, 2, 3) are:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0)

Note:

  • 1 ⇐ S.length ⇐ 200

  • S consists only of characters from the set {'D', 'I'}.

1
Unresolved directive in 0903-valid-permutations-for-di-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0903_ValidPermutationsForDISequence.java[]

904. Fruit Into Baskets

In a row of trees, the i-th tree produces fruit with type tree[i].

You start at any tree of your choice, then repeatedly perform the following steps:

  1. Add one piece of fruit from this tree to your baskets. If you cannot, stop.

  2. Move to the next tree to the right of the current tree. If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree: you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].

Example 2:

Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:

Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

  1. 1 ⇐ tree.length ⇐ 40000

  2. 0 ⇐ tree[i] < tree.length

1
Unresolved directive in 0904-fruit-into-baskets.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0904_FruitIntoBaskets.java[]

905. Sort Array By Parity

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:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Note:

  1. 1 ⇐ A.length ⇐ 5000

  2. 0 ⇐ A[i] ⇐ 5000

1
Unresolved directive in 0905-sort-array-by-parity.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0905_SortArrayByParity.java[]

906. Super Palindromes

Let’s say a positive integer is a superpalindrome if it is a palindrome, and it is also the square of a palindrome.

Now, given two positive integers L and R (represented as strings), return the number of superpalindromes in the inclusive range [L, R].

Example 1:

Input: L = "4", R = "1000"
Output: 4
Explanation: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.

Note:

  1. 1 ⇐ len(L) ⇐ 18

  2. 1 ⇐ len® ⇐ 18

  3. L and R are strings representing integers in the range [1, 10^18).

  4. int(L) ⇐ int®

1
Unresolved directive in 0906-super-palindromes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0906_SuperPalindromes.java[]

907. Sum of Subarray Minimums

Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.

Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:

Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.  Sum is 17.

Note:

  1. 1 ⇐ A.length ⇐ 30000

  2. 1 ⇐ A[i] ⇐ 30000

1
Unresolved directive in 0907-sum-of-subarray-minimums.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0907_SumOfSubarrayMinimums.java[]

908. Smallest Range I

Given an array A of integers, for each integer A[i] we may choose any x with -K ⇐ x ⇐ K, and add x to A[i].

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:

Input: A = [1], K = 0
Output: 0
Explanation: B = [1]

Example 2:

Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]

Example 3:

Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. 0 ⇐ A[i] ⇐ 10000

  3. 0 ⇐ K ⇐ 10000

1
Unresolved directive in 0908-smallest-range-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0908_SmallestRangeI.java[]

909. Snakes and Ladders

On an N x N board, the numbers from 1 to N*N are written boustrophedonically starting from the bottom left of the board, and alternating direction each row. For example, for a 6 x 6 board, the numbers are written as follows:

:https://assets.leetcode.com/uploads/2018/09/23/snakes.png" alt="snakes">

You start on square 1 of the board (which is always in the last row and first column). Each move, starting from square x, consists of the following:

  • You choose a destination square S with number x+1, x+2, x+3, x+4, x+5, or x+6, provided this number is ⇐ N*N.

  • (This choice simulates the result of a standard 6-sided die roll: ie., there are always at most 6 destinations, regardless of the size of the board.)

  • If S has a snake or ladder, you move to the destination of that snake or ladder. Otherwise, you move to S.

A board square on row r and column c has a "snake or ladder" if board[r][c] != -1. The destination of that snake or ladder is board[r][c].

Note that you only take a snake or ladder at most once per move: if the destination to a snake or ladder is the start of another snake or ladder, you do not continue moving. (For example, if the board is [[4,-1],[-1,3]], and on the first move your destination square is 2, then you finish your first move at 3, because you do not continue moving to 4.)

Return the least number of moves required to reach square <font face="monospace">N*N. If it is not possible, return -1.

Example 1:

Input: [
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,35,-1,-1,13,-1],
[-1,-1,-1,-1,-1,-1],
[-1,15,-1,-1,-1,-1]]
Output: 4
Explanation:
At the beginning, you start at square 1 [at row 5, column 0].
You decide to move to square 2, and must take the ladder to square 15.
You then decide to move to square 17 (row 3, column 5), and must take the snake to square 13.
You then decide to move to square 14, and must take the ladder to square 35.
You then decide to move to square 36, ending the game.
It can be shown that you need at least 4 moves to reach the N*N-th square, so the answer is 4.

Note:

  • 2 ⇐ board.length = board[0].length ⇐ 20

  • board[i][j] is between 1 and N*N or is equal to -1.

  • The board square with number 1 has no snake or ladder.

  • The board square with number N*N has no snake or ladder.

1
Unresolved directive in 0909-snakes-and-ladders.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0909_SnakesAndLadders.java[]

910. Smallest Range II

Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:

Input: A = [1], K = 0
Output: 0
Explanation: B = [1]

Example 2:

Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]

Example 3:

Input: A = [1,3,6], K = 3
Output: 3
Explanation: B = [4,6,3]

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. 0 ⇐ A[i] ⇐ 10000

  3. 0 ⇐ K ⇐ 10000

1
Unresolved directive in 0910-smallest-range-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0910_SmallestRangeII.java[]

911. Online Election

In an election, the i-th vote was cast for persons[i] at time times[i].

Now, we would like to implement the following query function: TopVotedCandidate.q(int t) will return the number of the person that was leading the election at time t.

Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.

Example 1:

Input: ["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
Output: [null,0,1,1,0,0,1]
Explanation:
At time 3, the votes are [0], and 0 is leading.
At time 12, the votes are [0,1,1], and 1 is leading.
At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)
This continues for 3 more queries at time 15, 24, and 8.

Note:

  1. 1 ⇐ persons.length = times.length ⇐ 5000

  2. 0 ⇐ persons[i] ⇐ persons.length

  3. times is a strictly increasing array with all elements in [0, 10^9].

  4. TopVotedCandidate.q is called at most 10000 times per test case.

  5. TopVotedCandidate.q(int t) is always called with t >= times[0].

1
Unresolved directive in 0911-online-election.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0911_OnlineElection.java[]

912. Sort an Array

Given an array of integers nums, sort the array in ascending order.

Example 1:

Input: nums = [5,2,3,1]
Output: [1,2,3,5]

Example 2:

Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]

Constraints:

  • 1 ⇐ nums.length ⇐ 50000

  • -50000 ⇐ nums[i] ⇐ 50000

1
Unresolved directive in 0912-sort-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0912_SortAnArray.java[]

913. Cat and Mouse

A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.

The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.

Mouse starts at node 1 and goes first, Cat starts at node 2 and goes second, and there is a Hole at node 0.

During each player’s turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].

Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)

Then, the game can end in 3 ways:

  • If ever the Cat occupies the same node as the Mouse, the Cat wins.

  • If ever the Mouse reaches the Hole, the Mouse wins.

  • If ever a position is repeated (ie. the players are in the same position as a previous turn, and it is the same player’s turn to move), the game is a draw.

Given a graph, and assuming both players play optimally, return 1 if the game is won by Mouse, 2 if the game is won by Cat, and 0 if the game is a draw.

Example 1:

Input: [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
Output: 0
Explanation:
4---3---1
|   |
2---5
 \ /
  0

Note:

  • 3 ⇐ graph.length ⇐ 50

  • It is guaranteed that graph[1] is non-empty.

  • It is guaranteed that graph[2] contains a non-zero element.

1
Unresolved directive in 0913-cat-and-mouse.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0913_CatAndMouse.java[]

914. X of a Kind in a Deck of Cards

In a deck of cards, each card has an integer written on it.

Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:

  • Each group has exactly X cards.

  • All the cards in each group have the same integer.

Example 1:

Input: [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]

Example 2:

Input: [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.

Example 3:

Input: [1]
Output: false
Explanation: No possible partition.

Example 4:

Input: [1,1]
Output: true
Explanation: Possible partition [1,1]

Example 5:

Input: [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2]

Note:

  • 1 ⇐ deck.length ⇐ 10000

  • 0 ⇐ deck[i] < 10000

1
Unresolved directive in 0914-x-of-a-kind-in-a-deck-of-cards.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0914_XOfAKindInADeckOfCards.java[]

915. Partition Array into Disjoint Intervals

Given an array A, partition it into two (contiguous) subarrays left and right so that:

  • Every element in left is less than or equal to every element in right.

  • left and right are non-empty.

  • left has the smallest possible size.

Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.

Example 1:

Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]

Example 2:

Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]

Note:

  • 2 ⇐ A.length ⇐ 30000

  • 0 ⇐ A[i] ⇐ 10^6

  • It is guaranteed there is at least one way to partition A as described.

1
Unresolved directive in 0915-partition-array-into-disjoint-intervals.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0915_PartitionArrayIntoDisjointIntervals.java[]

916. Word Subsets

We are given two arrays A and B of words. Each word is a string of lowercase letters.

Now, say that word b is a subset of word a* if every letter in b occurs in a, *including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world".

Now say a word a from A is universal if for every b in B, b is a subset of a.

Return a list of all universal words in A. You can return the words in any order.

Example 1:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
Output: ["facebook","google","leetcode"]

Example 2:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
Output: ["apple","google","leetcode"]

Example 3:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
Output: ["facebook","google"]

Example 4:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
Output: ["google","leetcode"]

Example 5:

Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
Output: ["facebook","leetcode"]

Note:

  1. 1 ⇐ A.length, B.length ⇐ 10000

  2. 1 ⇐ A[i].length, B[i].length ⇐ 10

  3. A[i] and B[i] consist only of lowercase letters.

  4. All words in A[i] are unique: there isn’t i != j with A[i] == A[j].

1
Unresolved directive in 0916-word-subsets.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0916_WordSubsets.java[]

917. Reverse Only Letters

Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

  1. S.length ⇐ 100

  2. 33 ⇐ S[i].ASCIIcode ⇐ 122

  3. S doesn’t contain \ or "

1
Unresolved directive in 0917-reverse-only-letters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0917_ReverseOnlyLetters.java[]

918. Maximum Sum Circular Subarray

Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C.

Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 ⇐ i < A.length, and C[i+A.length] = C[i] when i >= 0.)

Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], …​, C[j], there does not exist i ⇐ k1, k2 ⇐ j with k1 % A.length = k2 % A.length.)

Example 1:

Input: [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3

Example 2:

Input: [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10

Example 3:

Input: [3,-1,2,-1]
Output: 4
Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4

Example 4:

Input: [3,-2,2,-3]
Output: 3
Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3

Example 5:

Input: [-2,-3,-1]
Output: -1
Explanation: Subarray [-1] has maximum sum -1

*Note: *

  1. -30000 ⇐ A[i] ⇐ 30000

  2. 1 ⇐ A.length ⇐ 30000

1
Unresolved directive in 0918-maximum-sum-circular-subarray.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0918_MaximumSumCircularSubarray.java[]

919. Complete Binary Tree Inserter

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:

  • CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root;

  • CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;

  • CBTInserter.get_root() will return the head node of the tree.

Example 1:

Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
Output: [null,1,[1,2]]

Example 2:

Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
Output: [null,3,4,[1,2,3,4,5,6,7,8]]

Note:

  • The initial given tree is complete and contains between 1 and 1000 nodes.

  • CBTInserter.insert is called at most 10000 times per test case.

  • Every value of a given or inserted node is between 0 and 5000.

1
Unresolved directive in 0919-complete-binary-tree-inserter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0919_CompleteBinaryTreeInserter.java[]

920. Number of Music Playlists

Your music player contains N different songs and she wants to listen to L* *(not necessarily different) songs during your trip. You create a playlist so that:

  • Every song is played at least once

  • A song can only be played again only if K other songs have been played

Return the number of possible playlists. As the answer can be very large, return it modulo 10^9 + 7.

Example 1:

Input: N = 3, L = 3, K = 1
Output: 6
Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].

Example 2:

Input: N = 2, L = 3, K = 0
Output: 6
Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2]

Example 3:

Input: N = 2, L = 3, K = 1
Output: 2
Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2]

Note:

  • 0 ⇐ K < N ⇐ L ⇐ 100

1
Unresolved directive in 0920-number-of-music-playlists.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0920_NumberOfMusicPlaylists.java[]

921. Minimum Add to Make Parentheses Valid

Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or

  • It can be written as AB (A concatenated with B), where A and B are valid strings, or

  • It can be written as (A), where A is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

Note:

  • S.length ⇐ 1000

  • S only consists of '(' and ')' characters.

1
Unresolved directive in 0921-minimum-add-to-make-parentheses-valid.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0921_MinimumAddToMakeParenthesesValid.java[]

922. Sort Array By Parity II

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Note:

  1. 2 ⇐ A.length ⇐ 20000

  2. A.length % 2 == 0

  3. 0 ⇐ A[i] ⇐ 1000

1
Unresolved directive in 0922-sort-array-by-parity-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0922_SortArrayByParityII.java[]

923. 3Sum With Multiplicity

Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.

As the answer can be very large, return it modulo 10^9 + 7.

Example 1:

Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (A[i], A[j], A[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.

Example 2:

Input: A = [1,1,2,2,2,2], target = 5
Output: 12
Explanation:
A[i] = 1, A[j] = A[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.

Note:

  1. 3 ⇐ A.length ⇐ 3000

  2. 0 ⇐ A[i] ⇐ 100

  3. 0 ⇐ target ⇐ 300

1
Unresolved directive in 0923-3sum-with-multiplicity.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0923_3SumWithMultiplicity.java[]

924. Minimize Malware Spread

In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.

Some nodes initial are initially infected by malware. Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.

We will remove one node from the initial list. Return the node that if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:

Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0

Example 3:

Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1

Note:

  1. 1 < graph.length = graph[0].length ⇐ 300

  2. 0 ⇐ graph[i][j] == graph[j][i] ⇐ 1

  3. graph[i][i] = 1

  4. 1 ⇐ initial.length < graph.length

  5. 0 ⇐ initial[i] < graph.length

1
Unresolved directive in 0924-minimize-malware-spread.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0924_MinimizeMalwareSpread.java[]

925. Long Pressed Name

Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.

You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.

Example 1:

Input: name = "alex", typed = "aaleex"
Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.

Example 2:

Input: name = "saeed", typed = "ssaaedd"
Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.

Example 3:

Input: name = "leelee", typed = "lleeelee"
Output: true

Example 4:

Input: name = "laiden", typed = "laiden"
Output: true
Explanation: It's not necessary to long press any character.

Note:

  1. name.length ⇐ 1000

  2. typed.length ⇐ 1000

  3. The characters of name and typed are lowercase letters.

1
Unresolved directive in 0925-long-pressed-name.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0925_LongPressedName.java[]

926. Flip String to Monotone Increasing

A string of ’0'`s and ’1'`s is monotone increasing if it consists of some number of ’0'`s (possibly 0), followed by some number of ’1'`s (also possibly 0.)

We are given a string S of '0'`s and ’1'`s, and we may flip any ’0' to a '1' or a '1' to a '0'.

Return the minimum number of flips to make S monotone increasing.

Example 1:

Input: "00110"
Output: 1
Explanation: We flip the last digit to get 00111.

Example 2:

Input: "010110"
Output: 2
Explanation: We flip to get 011111, or alternatively 000111.

Example 3:

Input: "00011000"
Output: 2
Explanation: We flip to get 00000000.

Note:

  1. 1 ⇐ S.length ⇐ 20000

  2. S only consists of '0' and '1' characters.

1
Unresolved directive in 0926-flip-string-to-monotone-increasing.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0926_FlipStringToMonotoneIncreasing.java[]

927. Three Equal Parts

Given an array A of `0`s and `1`s, divide the array into 3 non-empty parts such that all of these parts represent the same binary value.

If it is possible, return any [i, j] with i+1 < j, such that:

  • A[0], A[1], …​, A[i] is the first part;

  • A[i+1], A[i+2], …​, A[j-1] is the second part, and

  • A[j], A[j+1], …​, A[A.length - 1] is the third part.

  • All three parts have equal binary value.

If it is not possible, return [-1, -1].

Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.

Example 1:

Input: [1,0,1,0,1]
Output: [0,3]

Example 2:

Input: [1,1,0,1,1]
Output: [-1,-1]

Note:

  • 3 ⇐ A.length ⇐ 30000

  • A[i] == 0 or A[i] == 1

1
Unresolved directive in 0927-three-equal-parts.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0927_ThreeEqualParts.java[]

928. Minimize Malware Spread II

(This problem is the same as Minimize Malware Spread, with the differences bolded.)

In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.

Some nodes initial are initially infected by malware. Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.

We will remove one node from the initial list, completely removing it and any connections from this node to any other node. Return the node that if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0

Example 2:

Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
Output: 1

Example 3:

Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
Output: 1

Note:

  1. 1 < graph.length = graph[0].length ⇐ 300

  2. 0 ⇐ graph[i][j] == graph[j][i] ⇐ 1

  3. graph[i][i] = 1

  4. 1 ⇐ initial.length < graph.length

  5. 0 ⇐ initial[i] < graph.length

1
Unresolved directive in 0928-minimize-malware-spread-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0928_MinimizeMalwareSpreadII.java[]

929. Unique Email Addresses

Every email consists of a local name and a domain name, separated by the @ sign.

For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.

Besides lowercase letters, these emails may contain ’.'`s or ’+'`s.

If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)

If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)

It is possible to use both of these rules at the same time.

Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?

Example 1:

Note:

  • 1 ⇐ emails[i].length ⇐ 100

  • 1 ⇐ emails.length ⇐ 100

  • Each emails[i] contains exactly one '@' character.

  • All local and domain names are non-empty.

  • Local names do not start with a '+' character.

1
Unresolved directive in 0929-unique-email-addresses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0929_UniqueEmailAddresses.java[]

930. Binary Subarrays With Sum

In an array A of 0`s and `1`s, how many non-empty subarrays have sum `S?

Example 1:

Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]

Note:

  1. A.length ⇐ 30000

  2. 0 ⇐ S ⇐ A.length

  3. A[i] is either 0 or 1.

1
Unresolved directive in 0930-binary-subarrays-with-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0930_BinarySubarraysWithSum.java[]

931. Minimum Falling Path Sum

Given a square array of integers A, we want the minimum sum of a falling path through A.

A falling path starts at any element in the first row, and chooses one element from each row. The next row’s choice must be in a column that is different from the previous row’s column by at most one.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 12
Explanation:
The possible falling paths are:
  • [1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]

  • [2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]

  • [3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]

The falling path with the smallest sum is [1,4,7], so the answer is 12.

Note:

  • 1 ⇐ A.length == A[0].length ⇐ 100

  • -100 ⇐ A[i][j] ⇐ 100

1
Unresolved directive in 0931-minimum-falling-path-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0931_MinimumFallingPathSum.java[]

932. Beautiful Array

For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, …​, N, such that:

For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].

Given N, return any beautiful array A. (It is guaranteed that one exists.)

Example 1:

Input: 4
Output: [2,1,4,3]

Example 2:

Input: 5
Output: [3,1,2,5,4]

Note:

  • 1 ⇐ N ⇐ 1000

1
Unresolved directive in 0932-beautiful-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0932_BeautifulArray.java[]

933. Number of Recent Calls

Write a class RecentCounter to count recent requests.

It has only one method: ping(int t), where t represents some time in milliseconds.

Return the number of `ping`s that have been made from 3000 milliseconds ago until now.

Any ping with time in [t - 3000, t] will count, including the current ping.

It is guaranteed that every call to ping uses a strictly larger value of t than before.

Example 1:

Input: inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]

Note:

  1. Each test case will have at most 10000 calls to ping.

  2. Each test case will call ping with strictly increasing values of t.

  3. Each call to ping will have 1 ⇐ t ⇐ 10^9.

1
Unresolved directive in 0933-number-of-recent-calls.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0933_NumberOfRecentCalls.java[]

934. Shortest Bridge

In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of `1`s not connected to any other 1s.)

Now, we may change `0`s to `1`s so as to connect the two islands together to form 1 island.

Return the smallest number of `0`s that must be flipped. (It is guaranteed that the answer is at least 1.)

Example 1:

Input: [[0,1],[1,0]]
Output: 1

Example 2:

Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 3:

Input: [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1

Note:

  1. 1 ⇐ A.length = A[0].length ⇐ 100

  2. A[i][j] == 0 or A[i][j] == 1

1
Unresolved directive in 0934-shortest-bridge.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0934_ShortestBridge.java[]

935. Knight Dialer

A chess knight can move as indicated in the chess diagram below:

] .           image::https://assets.leetcode.com/uploads/2018/10/30/keypad.png[

This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. Each hop must be from one key to another numbered key.

Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N digits total.

How many distinct numbers can you dial in this manner?

Since the answer may be large, output the answer modulo 10^9 + 7.

Example 1:

Input: 1
Output: 10

Example 2:

Input: 2
Output: 20

Example 3:

Input: 3
Output: 46

Note:

  • 1 ⇐ N ⇐ 5000

1
Unresolved directive in 0935-knight-dialer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0935_KnightDialer.java[]

936. Stamping The Sequence

You want to form a target string of lowercase letters.

At the beginning, your sequence is target.length '?' marks. You also have a stamp of lowercase letters.

On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to 10 * target.length turns.

For example, if the initial sequence is <font face="monospace">"?????", and your stamp is "abc", then you may make <font face="monospace">"abc??", "?abc?", "??abc" in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)

If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.

For example, if the sequence is <font face="monospace">"ababc", and the stamp is "abc", then we could return the answer [0, 2], corresponding to the moves <font face="monospace">"?????" → "abc??" → "ababc".

Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within 10 * target.length moves. Any answers specifying more than this number of moves will not be accepted.

Example 1:

Input: stamp = "abc", target = "ababc"
Output: [0,2]
([1,0,2] would also be accepted as an answer, as well as some other answers.)

Example 2:

Input: stamp = " abca", target = "aabcaca"
Output: [3,0,1]

Note:

  1. 1 ⇐ stamp.length ⇐ target.length ⇐ 1000

  2. stamp and target only contain lowercase letters.

1
Unresolved directive in 0936-stamping-the-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0936_StampingTheSequence.java[]

937. Reorder Data in Log Files

You have an array of logs. Each log is a space delimited string of words.

For each log, the first word in each log is an alphanumeric identifier. Then, either:

  • Each word after the identifier will consist only of lowercase letters, or;

  • Each word after the identifier will consist only of digits.

We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.

Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.

Return the final order of the logs.

Example 1:

Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]

Constraints:

  • 0 ⇐ logs.length ⇐ 100

  • 3 ⇐ logs[i].length ⇐ 100

  • logs[i] is guaranteed to have an identifier, and a word after the identifier.

1
Unresolved directive in 0937-reorder-data-in-log-files.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0937_ReorderDataInLogFiles.java[]

938. Range Sum of BST

Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).

The binary search tree is guaranteed to have unique values.

Example 1:

Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32

Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23

Note:

  1. The number of nodes in the tree is at most 10000.

  2. The final answer is guaranteed to be less than 2^31.

1
Unresolved directive in 0938-range-sum-of-bst.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0938_RangeSumOfBST.java[]

939. Minimum Area Rectangle

Given a set of points in the xy-plane, determine the minimum area of a rectangle formed from these points, with sides parallel to the x and y axes.

If there isn’t any rectangle, return 0.

Example 1:

Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4

Example 2:

Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
Output: 2

Note:

  1. 1 ⇐ points.length ⇐ 500

  2. 0 ⇐ points[i][0] ⇐ 40000

  3. 0 ⇐ points[i][1] ⇐ 40000

  4. All points are distinct.

1
Unresolved directive in 0939-minimum-area-rectangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0939_MinimumAreaRectangle.java[]

940. Distinct Subsequences II

Given a string S, count the number of distinct, non-empty subsequences of S .

Since the result may be large, return the answer modulo 10^9 + 7.

Example 1:

Input: "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".

Example 2:

Input: "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba".

Example 3:

Input: "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".

Note:

  1. S contains only lowercase letters.

  2. 1 ⇐ S.length ⇐ 2000

1
Unresolved directive in 0940-distinct-subsequences-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0940_DistinctSubsequencesII.java[]

941. Valid Mountain Array

Given an array A of integers, return true if and only if it is a valid mountain array.

Recall that A is a mountain array if and only if:

  • A.length >= 3

  • There exists some i with 0 < i < A.length - 1 such that:

  • `A[0] < A[1] < …​ A[i-1] < A[i] `

  • A[i] > A[i+1] > …​ > A[A.length - 1]

hint valid mountain array

Example 1:

Input: [2,1]
Output: false

Example 2:

Input: [3,5,5]
Output: false

Example 3:

Input: [0,3,2,1]
Output: true

Note:

  • 0 ⇐ A.length ⇐ 10000

  • `0 ⇐ A[i] ⇐ 10000 `

1
Unresolved directive in 0941-valid-mountain-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0941_ValidMountainArray.java[]

942. DI String Match

Given a string S that only contains "I" (increase) or "D" (decrease), let N = S.length.

Return any permutation A of [0, 1, …​, N] such that for all i = 0, …​, N-1:

  • If S[i] == "I", then A[i] < A[i+1]

  • If S[i] == "D", then A[i] > A[i+1]

Example 1:

Input: "IDID"
Output: [0,4,1,3,2]

Example 2:

Input: "III"
Output: [0,1,2,3]

Example 3:

Input: "DDI"
Output: [3,2,0,1]

Note:

  • 1 ⇐ S.length ⇐ 10000

  • S only contains characters "I" or "D".

1
Unresolved directive in 0942-di-string-match.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0942_DIStringMatch.java[]

943. Find the Shortest Superstring

Given an array A of strings, find any smallest string that contains each string in A as a substring.

We may assume that no string in A is substring of another string in A.

Example 1:

Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.

Example 2:

Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"

Note:

  1. 1 ⇐ A.length ⇐ 12

  2. 1 ⇐ A[i].length ⇐ 20

1
Unresolved directive in 0943-find-the-shortest-superstring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0943_FindTheShortestSuperstring.java[]

944. Delete Columns to Make Sorted

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = [“`abcdef”,"uvwxyz"]` and deletion indices {0, 2, 3}, then the final array after deletions is ["bef", "vyz"], and the remaining columns of A are ["b","v"], ["e","y"], and ["f","z"]. (Formally, the c-th column is [A[0][c], A[1][c], …​, A[A.length-1][c]].)

Suppose we chose a set of deletion indices D such that after deletions, each remaining column in A is in non-decreasing sorted order.

Return the minimum possible value of D.length.

Example 1:

Input: ["cba","daf","ghi"]
Output: 1
Explanation:
After choosing D = {1}, each column ["c","d","g"] and ["a","f","i"] are in non-decreasing sorted order.
If we chose D = {}, then a column ["b","a","h"] would not be in non-decreasing sorted order.

Example 2:

Input: ["a","b"]
Output: 0
Explanation: D = {}

Example 3:

Input: ["zyx","wvu","tsr"]
Output: 3
Explanation: D = {0, 1, 2}

Note:

  1. 1 ⇐ A.length ⇐ 100

  2. 1 ⇐ A[i].length ⇐ 1000

1
Unresolved directive in 0944-delete-columns-to-make-sorted.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0944_DeleteColumnsToMakeSorted.java[]

945. Minimum Increment to Make Array Unique

Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.

Return the least number of moves to make every value in A unique.

Example 1:

Input: [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].

Example 2:

Input: [3,2,1,2,1,7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.

Note:

  1. 0 ⇐ A.length ⇐ 40000

  2. 0 ⇐ A[i] < 40000

1
Unresolved directive in 0945-minimum-increment-to-make-array-unique.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0945_MinimumIncrementToMakeArrayUnique.java[]

946. Validate Stack Sequences

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Note:

  1. 0 ⇐ pushed.length == popped.length ⇐ 1000

  2. 0 ⇐ pushed[i], popped[i] < 1000

  3. pushed is a permutation of popped.

  4. pushed and popped have distinct values.

1
Unresolved directive in 0946-validate-stack-sequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0946_ValidateStackSequences.java[]

947. Most Stones Removed with Same Row or Column

On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.

Now, a move consists of removing a stone that shares a column or row with another stone on the grid.

What is the largest possible number of moves we can make?

Example 1:

Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5

Example 2:

Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3

Example 3:

Input: stones = [[0,0]]
Output: 0

Note:

  1. 1 ⇐ stones.length ⇐ 1000

  2. 0 ⇐ stones[i][j] < 10000

1
Unresolved directive in 0947-most-stones-removed-with-same-row-or-column.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0947_MostStonesRemovedWithSameRowOrColumn.java[]

948. Bag of Tokens

You have an initial power P, an initial score of 0 points, and a bag of tokens.

Each token can be used at most once, has a value token[i], and has potentially two ways to use it.

  • If we have at least token[i] power, we may play the token face up, losing token[i] power, and gaining 1 point.

  • If we have at least 1 point, we may play the token face down, gaining token[i] power, and losing 1 point.

Return the largest number of points we can have after playing any number of tokens.

Example 1:

Input: tokens = [100], P = 50
Output: 0

Example 2:

Input: tokens = [100,200], P = 150
Output: 1

Example 3:

Input: tokens = [100,200,300,400], P = 200
Output: 2

Note:

  • tokens.length ⇐ 1000

  • 0 ⇐ tokens[i] < 10000

  • 0 ⇐ P < 10000

1
Unresolved directive in 0948-bag-of-tokens.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0948_BagOfTokens.java[]

949. Largest Time for Given Digits

Given an array of 4 digits, return the largest 24 hour time that can be made.

The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.

Return the answer as a string of length 5. If no valid time can be made, return an empty string.

Example 1:

Input: [1,2,3,4]
Output: "23:41"

Example 2:

Input: [5,5,5,5]
Output: ""

Note:

  1. A.length == 4

  2. 0 ⇐ A[i] ⇐ 9

1
Unresolved directive in 0949-largest-time-for-given-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0949_LargestTimeForGivenDigits.java[]

950. Reveal Cards In Increasing Order

In a deck of cards, every card has a unique integer. You can order the deck in any order you want.

Initially, all the cards start face down (unrevealed) in one deck.

Now, you do the following steps repeatedly, until all cards are revealed:

  1. Take the top card of the deck, reveal it, and take it out of the deck.

  2. If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.

  3. If there are still unrevealed cards, go back to step 1. Otherwise, stop.

Return an ordering of the deck that would reveal the cards in increasing order.

The first entry in the answer is considered to be the top of the deck.

Example 1:

Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom.  The deck is now [13,17].
We reveal 13, and move 17 to the bottom.  The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.

Note:

  1. 1 ⇐ A.length ⇐ 1000

  2. 1 ⇐ A[i] ⇐ 10^6

  3. A[i] != A[j] for all i != j

1
Unresolved directive in 0950-reveal-cards-in-increasing-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0950_RevealCardsInIncreasingOrder.java[]

951. Flip Equivalent Binary Trees

For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.

A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.

Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1 and root2.

Example 1:

Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Output: true
Explanation: We flipped at nodes with values 1, 3, and 5.

:https://assets.leetcode.com/uploads/2018/11/29/tree_ex.png" alt="tree ex">

Note:

  1. Each tree will have at most 100 nodes.

  2. Each value in each tree will be a unique integer in the range [0, 99].

1
Unresolved directive in 0951-flip-equivalent-binary-trees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0951_FlipEquivalentBinaryTrees.java[]

952. Largest Component Size by Common Factor

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

  • There are A.length nodes, labelled A[0] 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:

Input: [4,6,15,35]
Output: 4

:https://assets.leetcode.com/uploads/2018/12/01/ex1.png" alt="ex1">

Example 2:

Input: [20,50,9,63]
Output: 2

:https://assets.leetcode.com/uploads/2018/12/01/ex2.png" alt="ex2">

Example 3:

Input: [2,3,6,7,4,12,21,39]
Output: 8

:https://assets.leetcode.com/uploads/2018/12/01/ex3.png" alt="ex3">

Note:

  • 1 ⇐ A.length ⇐ 20000

  • 1 ⇐ A[i] ⇐ 100000

1
Unresolved directive in 0952-largest-component-size-by-common-factor.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0952_LargestComponentSizeByCommonFactor.java[]

953. Verifying an Alien Dictionary

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

Example 1:

Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:

Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:

Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '&empty;', where '&empty;' is defined as the blank character which is less than any other character (https://en.wikipedia.org/wiki/Lexicographical_order[More info]).

Constraints:

  • 1 ⇐ words.length ⇐ 100

  • 1 ⇐ words[i].length ⇐ 20

  • order.length == 26

  • All characters in words[i] and order are English lowercase letters.

1
Unresolved directive in 0953-verifying-an-alien-dictionary.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0953_VerifyingAnAlienDictionary.java[]

954. Array of Doubled Pairs

Given an array of integers A with even length, return true if and only if it is possible to reorder it such that A[2 * i + 1] = 2 * A[2 * i] for every 0 ⇐ i < len(A) / 2.

Example 1:

Input: [3,1,3,6]
Output: false

Example 2:

Input: [2,1,2,6]
Output: false

Example 3:

Input: [4,-2,2,-4]
Output: true
Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].

Example 4:

Input: [1,2,4,16,8,4]
Output: false

Note:

  1. 0 ⇐ A.length ⇐ 30000

  2. A.length is even

  3. -100000 ⇐ A[i] ⇐ 100000

1
Unresolved directive in 0954-array-of-doubled-pairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0954_ArrayOfDoubledPairs.java[]

955. Delete Columns to Make Sorted II

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = ["abcdef","uvwxyz"] and deletion indices {0, 2, 3}, then the final array after deletions is ["bef","vyz"].

Suppose we chose a set of deletion indices D such that after deletions, the final array has its elements in lexicographic order (A[0] ⇐ A[1] ⇐ A[2] …​ ⇐ A[A.length - 1]).

Return the minimum possible value of D.length.

Example 1:

Input: ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.

Example 2:

Input: ["xc","yb","za"]
Output: 0
Explanation:
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)

Example 3:

Input: ["zyx","wvu","tsr"]
Output: 3
Explanation:
We have to delete every column.

Note:

  1. 1 ⇐ A.length ⇐ 100

  2. 1 ⇐ A[i].length ⇐ 100

1
Unresolved directive in 0955-delete-columns-to-make-sorted-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0955_DeleteColumnsToMakeSortedII.java[]

956. Tallest Billboard

You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.

You have a collection of rods which can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.

Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.

Example 1:

Input: [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.

Example 2:

Input: [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.

Example 3:

Input: [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.

Note:

  1. 0 ⇐ rods.length ⇐ 20

  2. 1 ⇐ rods[i] ⇐ 1000

  3. The sum of rods is at most 5000.

1
Unresolved directive in 0956-tallest-billboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0956_TallestBillboard.java[]

957. Prison Cells After N Days

There are 8 prison cells in a row, and each cell is either occupied or vacant.

Each day, whether the cell is occupied or vacant changes according to the following rules:

  • If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.

  • Otherwise, it becomes vacant.

(Note that because the prison is a row, the first and the last cells in the row can’t have two adjacent neighbors.)

We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.

Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)

Example 1:

Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation:
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]

Example 2:

Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]

Note:

  • cells.length == 8

  • cells[i] is in {0, 1}

  • 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 0957-prison-cells-after-n-days.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0957_PrisonCellsAfterNDays.java[]

958. Check Completeness of a Binary Tree

Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example 1:

complete binary tree 1
Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Example 2:

complete binary tree 2
Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.

Note:

  1. The tree will have between 1 and 100 nodes.

1
Unresolved directive in 0958-check-completeness-of-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0958_CheckCompletenessOfABinaryTree.java[]

959. Regions Cut By Slashes

In a N x N grid composed of 1 x 1 squares, each 1 x 1 square consists of a /, \, or blank space. These characters divide the square into contiguous regions.

(Note that backslash characters are escaped, so a \ is represented as "\\".)

Return the number of regions.

Example 1:

Input:
[
  " /",
  "/ "
]
Output: 2
Explanation: The 2x2 grid is as follows:

:https://assets.leetcode.com/uploads/2018/12/15/1.png" alt="1">

Example 2:

Input:
[
  " /",
  "  "
]
Output: 1
Explanation: The 2x2 grid is as follows:

:https://assets.leetcode.com/uploads/2018/12/15/2.png" alt="2">

Example 3:

Input:
[
  "\\/",
  "/\\"
]
Output: 4
Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)
The 2x2 grid is as follows:

:https://assets.leetcode.com/uploads/2018/12/15/3.png" alt="3">

Example 4:

Input:
[
  "/\\",
  "\\/"
]
Output: 5
Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.)
The 2x2 grid is as follows:

:https://assets.leetcode.com/uploads/2018/12/15/4.png" alt="4">

Example 5:

Input:
[
  "//",
  "/ "
]
Output: 3
Explanation: The 2x2 grid is as follows:

:https://assets.leetcode.com/uploads/2018/12/15/5.png" alt="5">

Note:

  1. 1 ⇐ grid.length == grid[0].length ⇐ 30

  2. grid[i][j] is either '/', '\', or ' '.

1
Unresolved directive in 0959-regions-cut-by-slashes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0959_RegionsCutBySlashes.java[]

960. Delete Columns to Make Sorted III

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = ["babca","bbazb"] and deletion indices {0, 1, 4}, then the final array after deletions is ["bc","az"].

Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.

For clarity, A[0] is in lexicographic order (ie. A[0][0] ⇐ A[0][1] ⇐ …​ ⇐ A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] ⇐ A[1][1] ⇐ …​ ⇐ A[1][A[1].length - 1]), and so on.

Return the minimum possible value of D.length.

Example 1:

Input: ["babca","bbazb"]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn't necessarily in lexicographic order.

Example 2:

Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.

Example 3:

Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.

Note:

  1. 1 ⇐ A.length ⇐ 100

  2. 1 ⇐ A[i].length ⇐ 100

1
Unresolved directive in 0960-delete-columns-to-make-sorted-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0960_DeleteColumnsToMakeSortedIII.java[]

961. N-Repeated Element in Size 2N Array

In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.

Return the element repeated N times.

Example 1:

Input: [1,2,3,3]
Output: 3

Example 2:

Input: [2,1,2,5,3,2]
Output: 2

Example 3:

Input: [5,1,5,2,5,3,5,4]
Output: 5

Note:

  1. 4 ⇐ A.length ⇐ 10000

  2. 0 ⇐ A[i] < 10000

  3. A.length is even

1
Unresolved directive in 0961-n-repeated-element-in-size-2n-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0961_NRepeatedElementInSize2NArray.java[]

962. Maximum Width Ramp

Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] ⇐ A[j]. The width of such a ramp is j - i.

Find the maximum width of a ramp in A. If one doesn’t exist, return 0.

Example 1:

Input: [6,0,8,2,1,5]
Output: 4
Explanation:
The maximum width ramp is achieved at (i, j) = (1, 5): A[1] = 0 and A[5] = 5.

Example 2:

Input: [9,8,1,0,1,9,4,0,4,1]
Output: 7
Explanation:
The maximum width ramp is achieved at (i, j) = (2, 9): A[2] = 1 and A[9] = 1.

Note:

  1. 2 ⇐ A.length ⇐ 50000

  2. 0 ⇐ A[i] ⇐ 50000

1
Unresolved directive in 0962-maximum-width-ramp.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0962_MaximumWidthRamp.java[]

963. Minimum Area Rectangle II

Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.

If there isn’t any rectangle, return 0.

Example 1:

1a
Input: [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.

Example 2:

2
Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.

Example 3:

3
Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
Output: 0
Explanation: There is no possible rectangle to form from these points.

Example 4:

4c
Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.

Note:

  1. 1 ⇐ points.length ⇐ 50

  2. 0 ⇐ points[i][0] ⇐ 40000

  3. 0 ⇐ points[i][1] ⇐ 40000

  4. All points are distinct.

  5. Answers within 10^-5 of the actual value will be accepted as correct.

1
Unresolved directive in 0963-minimum-area-rectangle-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0963_MinimumAreaRectangleII.java[]

964. Least Operators to Express Number

Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x …​ where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of <font face="monospace">3.

When writing such an expression, we adhere to the following conventions:

  • The division operator (/) returns rational numbers.

  • There are no parentheses placed anywhere.

  • We use the usual order of operations: multiplication and division happens before addition and subtraction.

  • It’s not allowed to use the unary negation operator (-). For example, “x - x” is a valid expression as it only uses subtraction, but “-x + x” is not because it uses negation.

We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.

Example 1:

Input: x = 3, target = 19
Output: 5
Explanation: 3  3 + 3  3 + 3 / 3.  The expression contains 5 operations.

Example 2:

Input: x = 5, target = 501
Output: 8
Explanation: 5  5  5  5 - 5  5 * 5 + 5 / 5.  The expression contains 8 operations.

Example 3:

Input: x = 100, target = 100000000
Output: 3
Explanation: 100  100  100 * 100.  The expression contains 3 operations.

Note:

  • 2 ⇐ x ⇐ 100

  • 1 ⇐ target ⇐ 2 * 10^8

1
Unresolved directive in 0964-least-operators-to-express-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0964_LeastOperatorsToExpressNumber.java[]

965. Univalued Binary Tree

A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

Example 1:

unival bst 1
Input: [1,1,1,1,1,null,1]
Output: true

Example 2:

unival bst 2
Input: [2,2,2,5,2]
Output: false

Note:

  1. The number of nodes in the given tree will be in the range [1, 100].

  2. Each node’s value will be an integer in the range [0, 99].

1
Unresolved directive in 0965-univalued-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0965_UnivaluedBinaryTree.java[]

966. Vowel Spellchecker

Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.

For a given query word, the spell checker handles two categories of spelling mistakes:

  • Capitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.

  • Example: wordlist = ["yellow"], query = "YellOw": correct = "yellow"

  • Example: wordlist = ["Yellow"], query = "yellow": correct = "Yellow"

  • Example: wordlist = ["yellow"], query = "yellow": correct = "yellow"

  • Vowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.

  • Example: wordlist = ["YellOw"], query = "yollow": correct = "YellOw"

  • Example: wordlist = ["YellOw"], query = "yeellow": correct = "" (no match)

  • Example: wordlist = ["YellOw"], query = "yllw": correct = "" (no match)

In addition, the spell checker operates under the following precedence rules:

  • When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.

  • When the query matches a word up to capitlization, you should return the first such match in the wordlist.

  • When the query matches a word up to vowel errors, you should return the first such match in the wordlist.

  • If the query has no matches in the wordlist, you should return the empty string.

Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].

Example 1:

Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"]
Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]

Note:

  • 1 ⇐ wordlist.length ⇐ 5000

  • 1 ⇐ queries.length ⇐ 5000

  • 1 ⇐ wordlist[i].length ⇐ 7

  • 1 ⇐ queries[i].length ⇐ 7

  • All strings in wordlist and queries consist only of english letters.

1
Unresolved directive in 0966-vowel-spellchecker.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0966_VowelSpellchecker.java[]

967. Numbers With Same Consecutive Differences

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:

Input: N = 3, K = 7
Output: [181,292,707,818,929]
Explanation: Note that 070 is not a valid number, because it has leading zeroes.

Example 2:

Input: N = 2, K = 1
Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]

Note:

  1. 1 ⇐ N ⇐ 9

  2. 0 ⇐ K ⇐ 9

1
Unresolved directive in 0967-numbers-with-same-consecutive-differences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0967_NumbersWithSameConsecutiveDifferences.java[]

968. Binary Tree Cameras

Given a binary tree, we install cameras on the nodes of the tree.

Each camera at a node can monitor its parent, itself, and its immediate children.

Calculate the minimum number of cameras needed to monitor all nodes of the tree.

Example 1:

bst cameras 01
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.

Example 2:

bst cameras 02
Input: [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.

Note:

  1. The number of nodes in the given tree will be in the range [1, 1000].

  2. Every node has value 0.

1
Unresolved directive in 0968-binary-tree-cameras.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0968_BinaryTreeCameras.java[]

969. Pancake Sorting

Given an array A, we can perform a pancake flip: We choose some positive integer k ⇐ A.length, then reverse the order of the first k elements of A. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A.

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

Example 1:

Input: [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: A = [3, 2, 4, 1]
After 1st flip (k=4): A = [1, 4, 2, 3]
After 2nd flip (k=2): A = [4, 1, 2, 3]
After 3rd flip (k=4): A = [3, 2, 1, 4]
After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted.

Example 2:

Input: [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.

Note:

  1. 1 ⇐ A.length ⇐ 100

  2. A[i] is a permutation of [1, 2, …​, A.length]

1
Unresolved directive in 0969-pancake-sorting.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0969_PancakeSorting.java[]

970. Powerful Integers

Given two positive integers x and y, an integer is powerful if it is equal to x^i + y^j for some integers i >= 0 and j >= 0.

Return a list of all powerful integers that have value less than or equal to bound.

You may return the answer in any order. In your answer, each value should occur at most once.

Example 1:

Input: x = 2, y = 3, bound = 10
Output: [2,3,4,5,7,9,10]
Explanation:
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
7 = 2^2 + 3^1
9 = 2^3 + 3^0
10 = 2^0 + 3^2

Example 2:

Input: x = 3, y = 5, bound = 15
Output: [2,4,6,8,10,14]

Note:

  • 1 ⇐ x ⇐ 100

  • 1 ⇐ y ⇐ 100

  • 0 ⇐ bound ⇐ 10^6

1
Unresolved directive in 0970-powerful-integers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0970_PowerfulIntegers.java[]

971. Flip Binary Tree To Match Preorder Traversal

Given a binary tree with N nodes, each node has a different value from {1, …​, N}.

A node in this binary tree can be flipped by swapping the left child and the right child of that node.

Consider the sequence of N values reported by a preorder traversal starting from the root. Call such a sequence of N values the voyage of the tree.

(Recall that a preorder traversal of a node means we report the current node’s value, then preorder-traverse the left child, then preorder-traverse the right child.)

Our goal is to flip the least number of nodes in the tree so that the voyage of the tree matches the voyage we are given.

If we can do so, then return a list of the values of all nodes flipped. You may return the answer in any order.

If we cannot do so, then return the list [-1].

Example 1:

1219 01
Input: root = [1,2], voyage = [2,1]
Output: [-1]

Example 2:

1219 02
Input: root = [1,2,3], voyage = [1,3,2]
Output: [1]

Example 3:

1219 02
Input: root = [1,2,3], voyage = [1,2,3]
Output: []

Note:

  1. 1 ⇐ N ⇐ 100

1
Unresolved directive in 0971-flip-binary-tree-to-match-preorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0971_FlipBinaryTreeToMatchPreorderTraversal.java[]

972. Equal Rational Numbers

Given two strings S and T, each of which represents a non-negative rational number, return True if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.

In general a rational number can be represented using up to three parts: an integer part, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways:

  • <IntegerPart> (e.g. 0, 12, 123)

  • <IntegerPart><.><NonRepeatingPart> (e.g. 0.5, 1., 2.12, 2.0001)

  • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> (e.g. 0.1(6), 0.9(9), 0.00(1212))

The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:

1 / 6 = 0.16666666…​ = 0.1(6) = 0.1666(6) = 0.166(66)

Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.

Example 1:

Input: S = "0.(52)", T = "0.5(25)"
Output: true
Explanation:
Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.

Example 2:

Input: S = "0.1666(6)", T = "0.166(66)"
Output: true

Example 3:

Input: S = "0.9(9)", T = "1."
Output: true
Explanation:
"0.9(9)" represents 0.999999999... repeated forever, which equals 1.  [https://en.wikipedia.org/wiki/0.999...[See this link for an explanation.]]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".

Note:

  • Each part consists only of digits.

  • The <IntegerPart> will not begin with 2 or more zeros. (There is no other restriction on the digits of each part.)

  • `1 ⇐ <IntegerPart>.length ⇐ 4 `

  • `0 ⇐ <NonRepeatingPart>.length ⇐ 4 `

  • 1 ⇐ <RepeatingPart>.length ⇐ 4

1
Unresolved directive in 0972-equal-rational-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0972_EqualRationalNumbers.java[]

973. K Closest Points to Origin

We have a list of points on the plane. Find the K closest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)

Example 1:

Input: points = [[1,3],[-2,2]], K = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], K = 2
Output: [[3,3],[-2,4]]
(The answer [[-2,4],[3,3]] would also be accepted.)

Note:

  1. 1 ⇐ K ⇐ points.length ⇐ 10000

  2. -10000 < points[i][0] < 10000

  3. -10000 < points[i][1] < 10000

1
Unresolved directive in 0973-k-closest-points-to-origin.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0973_KClosestPointsToOrigin.java[]

974. Subarray Sums Divisible by K

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

Example 1:

Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

Note:

  1. 1 ⇐ A.length ⇐ 30000

  2. -10000 ⇐ A[i] ⇐ 10000

  3. 2 ⇐ K ⇐ 10000

1
Unresolved directive in 0974-subarray-sums-divisible-by-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0974_SubarraySumsDivisibleByK.java[]

975. Odd Even Jump

You are given an integer array A. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, …​) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, …​) jumps in the series are called even numbered jumps.

You may from index i jump forward to index <font face="monospace">j (with i < j) in the following way:

  • During odd numbered jumps (ie. jumps 1, 3, 5, …​), you jump to the index <font face="monospace">j such that A[i] ⇐ A[j] and A[j] is the smallest possible value. If there are multiple such indexes <font face="monospace">j, you can only jump to the smallest such index <font face="monospace">j.

  • During even numbered jumps (ie. jumps 2, 4, 6, …​), you jump to the index <font face="monospace">j such that A[i] >= A[j] and A[j] is the largest possible value. If there are multiple such indexes <font face="monospace">j, you can only jump to the smallest such index <font face="monospace">j.

  • (It may be the case that for some index <font face="monospace">i, there are no legal jumps.)

A starting index is good if, starting from that index, you can reach the end of the array (index A.length - 1) by jumping some number of times (possibly 0 or more than once.)

Return the number of good starting indexes.

Example 1:

Input: [10,13,12,14,15]
Output: 2
Explanation:
From starting index i = 0, we can jump to i = 2 (since A[2] is the smallest among A[1], A[2], A[3], A[4] that is greater or equal to A[0]), then we can't jump any more.
From starting index i = 1 and i = 2, we can jump to i = 3, then we can't jump any more.
From starting index i = 3, we can jump to i = 4, so we've reached the end.
From starting index i = 4, we've reached the end already.
In total, there are 2 different starting indexes (i = 3, i = 4) where we can reach the end with some number of jumps.

Example 2:

Input: [2,3,1,1,4]
Output: 3
Explanation:
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:

During our 1st jump (odd numbered), we first jump to i = 1 because A[1] is the smallest value in (A[1], A[2], A[3], A[4]) that is greater than or equal to A[0].

During our 2nd jump (even numbered), we jump from i = 1 to i = 2 because A[2] is the largest value in (A[2], A[3], A[4]) that is less than or equal to A[1].  A[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3.

During our 3rd jump (odd numbered), we jump from i = 2 to i = 3 because A[3] is the smallest value in (A[3], A[4]) that is greater than or equal to A[2].

We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.

In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indexes (i = 1, i = 3, i = 4) where we can reach the end with some number of jumps.

Example 3:

Input: [5,1,3,4,2]
Output: 3
Explanation:
We can reach the end from starting indexes 1, 2, and 4.

Note:

  • 1 ⇐ A.length ⇐ 20000

  • 0 ⇐ A[i] < 100000

1
Unresolved directive in 0975-odd-even-jump.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0975_OddEvenJump.java[]

976. Largest Perimeter Triangle

Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.

If it is impossible to form any triangle of non-zero area, return 0.

Example 1:

Input: [2,1,2]
Output: 5

Example 2:

Input: [1,2,1]
Output: 0

Example 3:

Input: [3,2,3,4]
Output: 10

Example 4:

Input: [3,6,2,3]
Output: 8

Note:

  1. 3 ⇐ A.length ⇐ 10000

  2. 1 ⇐ A[i] ⇐ 10^6

1
Unresolved directive in 0976-largest-perimeter-triangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0976_LargestPerimeterTriangle.java[]

977. Squares of a Sorted Array

Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.

Example 1:

Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]

Example 2:

Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. -10000 ⇐ A[i] ⇐ 10000

  3. A is sorted in non-decreasing order.

1
Unresolved directive in 0977-squares-of-a-sorted-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0977_SquaresOfASortedArray.java[]

978. Longest Turbulent Subarray

A subarray A[i], A[i+1], …​, A[j] of A is said to be turbulent if and only if:

  • For i ⇐ k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;

  • OR, for i ⇐ k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.

That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

Return the length of a maximum size turbulent subarray of A.

Example 1:

Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])

Example 2:

Input: [4,8,12,16]
Output: 2

Example 3:

Input: [100]
Output: 1

Note:

  • 1 ⇐ A.length ⇐ 40000

  • 0 ⇐ A[i] ⇐ 10^9

1
Unresolved directive in 0978-longest-turbulent-subarray.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0978_LongestTurbulentSubarray.java[]

979. Distribute Coins in Binary Tree

Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.

In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)

Return the number of moves required to make every node have exactly one coin.

Example 1:

tree1
Input: [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.

Example 2:

tree2
Input: [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves].  Then, we move one coin from the root of the tree to the right child.

Example 3:

tree3
Input: [1,0,2]
Output: 2

Example 4:

tree4
Input: [1,0,0,null,3]
Output: 4

Note:

  1. 1⇐ N ⇐ 100

  2. 0 ⇐ node.val ⇐ N

1
Unresolved directive in 0979-distribute-coins-in-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0979_DistributeCoinsInBinaryTree.java[]

980. Unique Paths III

On a 2-dimensional grid, there are 4 types of squares:

  • 1 represents the starting square. There is exactly one starting square.

  • 2 represents the ending square. There is exactly one ending square.

  • 0 represents empty squares we can walk over.

  • -1 represents obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

Example 1:

Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Explanation: We have the following two paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)

Example 2:

Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
Explanation: We have the following four paths:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)

Example 3:

Input: [[0,1],[2,0]]
Output: 0
Explanation:
There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.

Note:

  • 1 ⇐ grid.length * grid[0].length ⇐ 20

1
Unresolved directive in 0980-unique-paths-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0980_UniquePathsIII.java[]

981. Time Based Key-Value Store

Create a timebased key-value store class TimeMap, that supports two operations.

  1. set(string key, string value, int timestamp)

    • Stores the key and value, along with the given timestamp.

  2. get(string key, int timestamp)

    • Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev ⇐ timestamp.

    • If there are multiple such values, it returns the one with the largest timestamp_prev.

    • If there are no values, it returns the empty string ("").

Example 1:

Input: inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1);  // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"

Example 2:

Input: inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]]
Output: [null,null,null,"","high","high","low","low"]

Note:

  • All key/value strings are lowercase.

  • All key/value strings have length in the range [1, 100]

  • The timestamps for all TimeMap.set operations are strictly increasing.

  • 1 ⇐ timestamp ⇐ 10^7

  • TimeMap.set and TimeMap.get functions will be called a total of 120000 times (combined) per test case.

1
Unresolved directive in 0981-time-based-key-value-store.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0981_TimeBasedKeyValueStore.java[]

982. Triples with Bitwise AND Equal To Zero

Given an array of integers A, find the number of triples of indices (i, j, k) such that:

  • 0 ⇐ i < A.length

  • 0 ⇐ j < A.length

  • 0 ⇐ k < A.length

  • A[i] & A[j] & A[k] == 0, where & represents the bitwise-AND operator.

Example 1:

Input: [2,1,3]
Output: 12
Explanation: We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 &amp; 2 &amp; 1
(i=0, j=1, k=0) : 2 &amp; 1 &amp; 2
(i=0, j=1, k=1) : 2 &amp; 1 &amp; 1
(i=0, j=1, k=2) : 2 &amp; 1 &amp; 3
(i=0, j=2, k=1) : 2 &amp; 3 &amp; 1
(i=1, j=0, k=0) : 1 &amp; 2 &amp; 2
(i=1, j=0, k=1) : 1 &amp; 2 &amp; 1
(i=1, j=0, k=2) : 1 &amp; 2 &amp; 3
(i=1, j=1, k=0) : 1 &amp; 1 &amp; 2
(i=1, j=2, k=0) : 1 &amp; 3 &amp; 2
(i=2, j=0, k=1) : 3 &amp; 2 &amp; 1
(i=2, j=1, k=0) : 3 &amp; 1 &amp; 2

Note:

  • <font face="monospace">1 ⇐ A.length ⇐ 1000

  • 0 ⇐ A[i] < 2^16

1
Unresolved directive in 0982-triples-with-bitwise-and-equal-to-zero.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0982_TriplesWithBitwiseANDEqualToZero.java[]

983. Minimum Cost For Tickets

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[0] dollars;

  • a 7-day pass is sold for costs[1] dollars;

  • a 30-day pass is sold for costs[2] 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:

Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total you spent $11 and covered all the days of your travel.

Example 2:

Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total you spent $17 and covered all the days of your travel.

Note:

  • 1 ⇐ days.length ⇐ 365

  • 1 ⇐ days[i] ⇐ 365

  • days is in strictly increasing order.

  • costs.length == 3

  • 1 ⇐ costs[i] ⇐ 1000

1
Unresolved directive in 0983-minimum-cost-for-tickets.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0983_MinimumCostForTickets.java[]

984. String Without AAA or BBB

Given two integers A and B, return any string S such that:

  • S has length A + B and contains exactly A 'a' letters, and exactly B 'b' letters;

  • The substring 'aaa' does not occur in S;

  • The substring 'bbb' does not occur in S.

Example 1:

Input: A = 1, B = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

Input: A = 4, B = 1
Output: "aabaa"

Note:

  • 0 ⇐ A ⇐ 100

  • 0 ⇐ B ⇐ 100

  • It is guaranteed such an S exists for the given A and B.

1
Unresolved directive in 0984-string-without-aaa-or-bbb.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0984_StringWithoutAAAOrBBB.java[]

985. Sum of Even Numbers After Queries

We have an array A of integers, and an array queries of queries.

For the i-th query val = queries[i][0], index = queries[i][1], we add <font face="monospace">val to A[index]. Then, the answer to the i-th query is the sum of the even values of A.

(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifies the array A.)

Return the answer to all queries. Your answer array should have answer[i] as the answer to the i-th query.

Example 1:

Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
Output: [8,6,2,4]
Explanation:
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. -10000 ⇐ A[i] ⇐ 10000

  3. 1 ⇐ queries.length ⇐ 10000

  4. -10000 ⇐ queries[i][0] ⇐ 10000

  5. 0 ⇐ queries[i][1] < A.length

1
Unresolved directive in 0985-sum-of-even-numbers-after-queries.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0985_SumOfEvenNumbersAfterQueries.java[]

986. Interval List Intersections

Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

(Formally, a closed interval [a, b] (with a ⇐ b) denotes the set of real numbers x with a ⇐ x ⇐ b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)

Example 1:

image::https://assets.leetcode.com/uploads/2019/01/30/interval1.png[]

Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Reminder: The inputs and the desired output are lists of Interval objects, and not arrays or lists.

Note:

  1. 0 ⇐ A.length < 1000

  2. 0 ⇐ B.length < 1000

  3. 0 ⇐ A[i].start, A[i].end, B[i].start, B[i].end < 10^9

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

1
Unresolved directive in 0986-interval-list-intersections.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0986_IntervalListIntersections.java[]

987. Vertical Order Traversal of a Binary Tree

Given a binary tree, return the vertical order traversal of its nodes values.

For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).

Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).

If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.

Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.

Example 1:

1236 example 1
Input: [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Without loss of generality, we can assume the root node is at position (0, 0):
Then, the node with value 9 occurs at position (-1, -1);
The nodes with values 3 and 15 occur at positions (0, 0) and (0, -2);
The node with value 20 occurs at position (1, -1);
The node with value 7 occurs at position (2, -2).

Example 2:

tree2
Input: [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
The node with value 5 and the node with value 6 have the same position according to the given scheme.
However, in the report "[1,5,6]", the node value of 5 comes first since 5 is smaller than 6.

Note:

  1. The tree will have between <font face="monospace">1 and 1000 nodes.

  2. Each node’s value will be between 0 and 1000.

1
Unresolved directive in 0987-vertical-order-traversal-of-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0987_VerticalOrderTraversalOfABinaryTree.java[]

988. Smallest String Starting From Leaf

Given the root of a binary tree, each node has a value from 0 to 25 representing the letters 'a' to 'z': a value of 0 represents 'a', a value of 1 represents 'b', and so on.

Find the lexicographically smallest string that starts at a leaf of this tree and ends at the root.

(As a reminder, any shorter prefix of a string is lexicographically smaller: for example, "ab" is lexicographically smaller than "aba". A leaf of a node is a node that has no children.)

Example 1:

image::https://assets.leetcode.com/uploads/2019/01/30/tree1.png[]

Input: [0,1,2,3,4,3,4]
Output: "dba"

Example 2:

tree2
Input: [25,1,3,1,3,0,2]
Output: "adz"

Example 3:

tree3
Input: [2,2,1,null,1,0,null,0]
Output: "abc"

Note:

  1. The number of nodes in the given tree will be between 1 and 8500.

  2. Each node in the tree will have a value between 0 and 25.

1
Unresolved directive in 0988-smallest-string-starting-from-leaf.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0988_SmallestStringStartingFromLeaf.java[]

989. Add to Array-Form of Integer

For a non-negative integer X, the array-form of X` is an array of its digits in left to right order. For example, if `X = 1231, then the array form is [1,2,3,1].

Given the array-form A of a non-negative integer X, return the array-form of the integer X+K.

Example 1:

Input: A = [1,2,0,0], K = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: A = [2,7,4], K = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: A = [2,1,5], K = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

Example 4:

Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1
Output: [1,0,0,0,0,0,0,0,0,0,0]
Explanation: 9999999999 + 1 = 10000000000

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. 0 ⇐ A[i] ⇐ 9

  3. 0 ⇐ K ⇐ 10000

  4. If A.length > 1, then A[0] != 0

1
Unresolved directive in 0989-add-to-array-form-of-integer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0989_AddToArrayFormOfInteger.java[]

990. Satisfiability of Equality Equations

Given an array <font face="monospace">equations of strings that represent relationships between variables, each string equations[i] has length 4 and takes one of two different forms: "a==b" or "a!=b". Here, a and b are lowercase letters (not necessarily different) that represent one-letter variable names.

Return true if and only if it is possible to assign integers to variable names so as to satisfy all the given equations.

Example 1:

Input: ["a==b","b!=a"]
Output: false
Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.  There is no way to assign the variables to satisfy both equations.

Example 2:

Input: ["b==a","a==b"]
Output: true
Explanation: We could assign a = 1 and b = 1 to satisfy both equations.

Example 3:

Input: ["a==b","b==c","a==c"]
Output: true

Example 4:

Input: ["a==b","b!=c","c==a"]
Output: false

Example 5:

Input: ["c==c","b==d","x!=z"]
Output: true

Note:

  1. 1 ⇐ equations.length ⇐ 500

  2. equations[i].length == 4

  3. equations[i][0] and equations[i][3] are lowercase letters

  4. equations[i][1] is either '=' or '!'

  5. equations[i][2] is '='

1
Unresolved directive in 0990-satisfiability-of-equality-equations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0990_SatisfiabilityOfEqualityEquations.java[]

991. Broken Calculator

On a broken calculator that has a number showing on its display, we can perform two operations:

  • Double: Multiply the number on the display by 2, or;

  • Decrement: Subtract 1 from the number on the display.

Initially, the calculator is displaying the number X.

Return the minimum number of operations needed to display the number Y.

Example 1:

Input: X = 2, Y = 3
Output: 2
Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.

Example 2:

Input: X = 5, Y = 8
Output: 2
Explanation: Use decrement and then double {5 -> 4 -> 8}.

Example 3:

Input: X = 3, Y = 10
Output: 3
Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.

Example 4:

Input: X = 1024, Y = 1
Output: 1023
Explanation: Use decrement operations 1023 times.

Note:

  • 1 ⇐ X ⇐ 10^9

  • 1 ⇐ Y ⇐ 10^9

1
Unresolved directive in 0991-broken-calculator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0991_BrokenCalculator.java[]

992. Subarrays with K Different Integers

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.

(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)

Return the number of good subarrays of A.

Example 1:
Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].
Example 2:
Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

  • 1 ⇐ A.length ⇐ 20000

  • 1 ⇐ A[i] ⇐ A.length

  • 1 ⇐ K ⇐ A.length

解题分析

解题中心思路是滑动窗口。

思考题

这个解题方案怎么理解?

参考资料

Given an array A of positive integers, call a (contiguous, not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly K.

(For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.)

Return the number of good subarrays of A.

Example 1:

Input: A = [1,2,1,2,3], K = 2
Output: 7
Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2].

Example 2:

Input: A = [1,2,1,3,4], K = 3
Output: 3
Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].

Note:

  1. 1 ⇐ A.length ⇐ 20000

  2. 1 ⇐ A[i] ⇐ A.length

  3. 1 ⇐ K ⇐ A.length

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.diguage.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * = 992. Subarrays with K Different Integers
 *
 * https://leetcode.com/problems/subarrays-with-k-different-integers/[Subarrays with K Different Integers - LeetCode]
 *
 * @author D瓜哥, https://www.diguage.com/
 * @since 2020-01-30 19:44
 */
public class _0992_SubarraysWithKDifferentIntegers {
    /**
     * Runtime: 5 ms, faster than 93.74% of Java online submissions for Subarrays with K Different Integers.
     * Memory Usage: 51.9 MB, less than 5.26% of Java online submissions for Subarrays with K Different Integers.
     *
     * Copy from: https://mp.weixin.qq.com/s/6YeZUCYj5ft-OGa85sQegw[面试官,你再问我滑动窗口问题试试?我有解题模板,不怕!]
     */
    public int subarraysWithKDistinct(int[] A, int K) {
        if (Objects.isNull(A) || A.length == 0 || A.length < K) {
            return 0;
        }
        int[] hash = new int[A.length + 1];
        int left = 0, count = 0;
        int results = 0, result = 1;
        for (int right = 0; right < A.length; right++) {
            hash[A[right]]++;
            if (hash[A[right]] == 1) {
                count++;
            }
            while (hash[A[left]] > 1 || count > K) {
                if (count > K) {
                    result = 1;
                    count--;
                } else {
                    result++;
                }
                hash[A[left]]--;
                left++;
            }
            if (count == K) {
                results += result;
            }
        }
        return results;
    }

    /**
     * Runtime: 53 ms, faster than 67.75% of Java online submissions for Subarrays with K Different Integers.
     * Memory Usage: 43.9 MB, less than 10.53% of Java online submissions for Subarrays with K Different Integers.
     *
     * Copy from: https://leetcode-cn.com/problems/subarrays-with-k-different-integers/solution/k-ge-bu-tong-zheng-shu-de-zi-shu-zu-by-leetcode/[K 个不同整数的子数组 - K 个不同整数的子数组 - 力扣(LeetCode)]
     */
    public int subarraysWithKDistinctWindows(int[] A, int K) {
        if (Objects.isNull(A) || A.length == 0 || A.length < K) {
            return 0;
        }
        Window w1 = new Window();
        Window w2 = new Window();
        int result = 0;
        int left1 = 0, left2 = 0;
        for (int right = 0; right < A.length; right++) {
            int x = A[right];
            w1.add(x);
            w2.add(x);
            while (w1.different() > K) {
                w1.remove(A[left1++]);
            }
            while (w2.different() >= K) {
                w2.remove(A[left2++]);
            }
            result += left2 - left1;
        }
        return result;
    }

    private class Window {
        Map<Integer, Integer> count;
        int nonzeo;

        public Window() {
            count = new HashMap<>();
            nonzeo = 0;
        }

        void add(int x) {
            count.put(x, count.getOrDefault(x, 0) + 1);
            if (count.get(x) == 1) {
                nonzeo++;
            }
        }

        void remove(int x) {
            count.put(x, count.get(x) - 1);
            if (count.get(x) == 0) {
                nonzeo--;
            }
        }

        int different() {
            return nonzeo;
        }
    }

    public static void main(String[] args) {
        _0992_SubarraysWithKDifferentIntegers solution = new _0992_SubarraysWithKDifferentIntegers();
        int[] n1 = {1, 2, 1, 2, 3};
        int r1 = solution.subarraysWithKDistinct(n1, 2);
        System.out.println((r1 == 7) + " : " + r1);

        int[] n2 = {1, 2, 1, 3, 4};
        int r2 = solution.subarraysWithKDistinct(n2, 3);
        System.out.println((r2 == 3) + " : " + r2);
    }
}

993. Cousins in Binary Tree

In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.

Two nodes of a binary tree are cousins if they have the same depth, but have different parents.

We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.

Return true if and only if the nodes corresponding to the values x and y are cousins.

*Example 1:

image::https://assets.leetcode.com/uploads/2019/02/12/q1248-01.png[]*

Input: root = [1,2,3,4], x = 4, y = 3
Output: false

*Example 2:

image::https://assets.leetcode.com/uploads/2019/02/12/q1248-02.png[]*

Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true

Example 3:

q1248 03
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false

Note:

  1. The number of nodes in the tree will be between 2 and 100.

  2. Each node has a unique integer value from 1 to 100.

1
Unresolved directive in 0993-cousins-in-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0993_CousinsInBinaryTree.java[]

994. Rotting Oranges

In a given grid, each cell can have one of three values:

  • the value 0 representing an empty cell;

  • the value 1 representing a fresh orange;

  • the value 2 representing a rotten orange.

Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.

Example 1:

oranges
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4

Example 2:

Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.

Example 3:

Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Note:

  • 1 ⇐ grid.length ⇐ 10

  • 1 ⇐ grid[0].length ⇐ 10

  • grid[i][j] is only 0, 1, or 2.

1
Unresolved directive in 0994-rotting-oranges.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0994_RottingOranges.java[]

995. Minimum Number of K Consecutive Bit Flips

In an array A containing only 0s and 1s, a _`K`-bit flip _consists of choosing a (contiguous) subarray of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.

Return the minimum number of K-bit flips required so that there is no 0 in the array. If it is not possible, return -1.

Example 1:

Input: A = [0,1,0], K = 1
Output: 2
Explanation: Flip A[0], then flip A[2].

Example 2:

Input: A = [1,1,0], K = 2
Output: -1
Explanation: No matter how we flip subarrays of size 2, we can't make the array become [1,1,1].

Example 3:

Input: A = [0,0,0,1,0,1,1,0], K = 3
Output: 3
Explanation:
Flip A[0],A[1],A[2]: A becomes [1,1,1,1,0,1,1,0]
Flip A[4],A[5],A[6]: A becomes [1,1,1,1,1,0,0,0]
Flip A[5],A[6],A[7]: A becomes [1,1,1,1,1,1,1,1]

Note:

  1. 1 ⇐ A.length ⇐ 30000

  2. 1 ⇐ K ⇐ A.length

1
Unresolved directive in 0995-minimum-number-of-k-consecutive-bit-flips.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0995_MinimumNumberOfKConsecutiveBitFlips.java[]

996. Number of Squareful Arrays

Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.

Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].

Example 1:

Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.

Example 2:

Input: [2,2,2]
Output: 1

Note:

  1. 1 ⇐ A.length ⇐ 12

  2. 0 ⇐ A[i] ⇐ 1e9

1
Unresolved directive in 0996-number-of-squareful-arrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0996_NumberOfSquarefulArrays.java[]

997. Find the Town Judge

In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

  1. The town judge trusts nobody.

  2. Everybody (except for the town judge) trusts the town judge.

  3. There is exactly one person that satisfies properties 1 and 2.

You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b.

If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1.

Example 1:

Input: N = 2, trust = [[1,2]]
Output: 2

Example 2:

Input: N = 3, trust = [[1,3],[2,3]]
Output: 3

Example 3:

Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1

Example 4:

Input: N = 3, trust = [[1,2],[2,3]]
Output: -1

Example 5:

Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3

Note:

  1. 1 ⇐ N ⇐ 1000

  2. trust.length ⇐ 10000

  3. trust[i] are all different

  4. trust[i][0] != trust[i][1]

  5. 1 ⇐ trust[i][0], trust[i][1] ⇐ N

1
Unresolved directive in 0997-find-the-town-judge.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0997_FindTheTownJudge.java[]

998. Maximum Binary Tree II

We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

Just as in the <a href="https://leetcode.com/problems/maximum-binary-tree/">previous problem</a>, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

  • If A is empty, return null.

  • Otherwise, let A[i] be the largest element of A. Create a root node with value A[i].

  • The left child of root will be Construct([A[0], A[1], …​, A[i-1]])

  • The right child of root will be Construct([A[i+1], A[i+2], …​, A[A.length - 1]])

  • Return root.

Note that we were not given A directly, only a root node root = Construct(A).

Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.

Return Construct(B).

Example 1:

]image::https://assets.leetcode.com/uploads/2019/02/21/maximum-binary-tree-1-2.png[
Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]

*Example 2:

image::https://assets.leetcode.com/uploads/2019/02/21/maximum-binary-tree-2-1.png[]image::https://assets.leetcode.com/uploads/2019/02/21/maximum-binary-tree-2-2.png[]*

Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]

*Example 3:

image::https://assets.leetcode.com/uploads/2019/02/21/maximum-binary-tree-3-1.png[]image::https://assets.leetcode.com/uploads/2019/02/21/maximum-binary-tree-3-2.png[]*

Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]

Note:

  • 1 ⇐ B.length ⇐ 100

1
Unresolved directive in 0998-maximum-binary-tree-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0998_MaximumBinaryTreeII.java[]

999. Available Captures for Rook

On an 8 x 8 chessboard, there is one white rook. There also may be empty squares, white bishops, and black pawns. These are given as characters 'R', '.', 'B', and 'p' respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.

The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies. Also, rooks cannot move into the same square as other friendly bishops.

Return the number of pawns the rook can capture in one move.

Example 1:

1253 example 1 improved
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
In this example the rook is able to capture all the pawns.

Example 2:

1253 example 2 improved
Input: [[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 0
Explanation:
Bishops are blocking the rook to capture any pawn.

Example 3:

1253 example 3 improved
Input: [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
Output: 3
Explanation:
The rook can capture the pawns at positions b5, d6 and f5.

Note:

  1. board.length == board[i].length == 8

  2. board[i][j] is either 'R', '.', 'B', or 'p'

  3. There is exactly one cell with board[i][j] == 'R'

1
Unresolved directive in 0999-available-captures-for-rook.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_0999_AvailableCapturesForRook.java[]

1000. Minimum Cost to Merge Stones

There are N piles of stones arranged in a row. The i-th pile has stones[i] stones.

A move consists of merging exactly K consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these K piles.

Find the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.

Example 1:

Input: stones = [3,2,4,1], K = 2
Output: 20
Explanation:
We start with [3, 2, 4, 1].
We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].
We merge [4, 1] for a cost of 5, and we are left with [5, 5].
We merge [5, 5] for a cost of 10, and we are left with [10].
The total cost was 20, and this is the minimum possible.

Example 2:

Input: stones = [3,2,4,1], K = 3
Output: -1
Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore.  So the task is impossible.

Example 3:

Input: stones = [3,5,1,2,6], K = 3
Output: 25
Explanation:
We start with [3, 5, 1, 2, 6].
We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].
We merge [3, 8, 6] for a cost of 17, and we are left with [17].
The total cost was 25, and this is the minimum possible.

Note:

  • 1 ⇐ stones.length ⇐ 30

  • 2 ⇐ K ⇐ 30

  • 1 ⇐ stones[i] ⇐ 100

1
Unresolved directive in 1000-minimum-cost-to-merge-stones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1000_MinimumCostToMergeStones.java[]

1001. Grid Illumination

On a N x N grid of cells, each cell (x, y) with 0 ⇐ x < N and 0 ⇐ y < N has a lamp.

Initially, some number of lamps are on. lamps[i] tells us the location of the i-th lamp that is on. Each lamp that is on illuminates every square on its x-axis, y-axis, and both diagonals (similar to a Queen in chess).

For the i-th query queries[i] = (x, y), the answer to the query is 1 if the cell (x, y) is illuminated, else 0.

After each query (x, y) [in the order given by queries], we turn off any lamps that are at cell (x, y) or are adjacent 8-directionally (ie., share a corner or edge with cell (x, y).)

Return an array of answers. Each value answer[i] should be equal to the answer of the i-th query queries[i].

Example 1:

Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
Explanation:
Before performing the first query we have both lamps [0,0] and [4,4] on.
The grid representing which cells are lit looks like this, where [0,0] is the top left corner, and [4,4] is the bottom right corner:
1 1 1 1 1
1 1 0 0 1
1 0 1 0 1
1 0 0 1 1
1 1 1 1 1
Then the query at [1, 1] returns 1 because the cell is lit.  After this query, the lamp at [0, 0] turns off, and the grid now looks like this:
1 0 0 0 1
0 1 0 0 1
0 0 1 0 1
0 0 0 1 1
1 1 1 1 1
Before performing the second query we have only the lamp [4,4] on.  Now the query at [1,0] returns 0, because the cell is no longer lit.

Note:

  1. 1 ⇐ N ⇐ 10^9

  2. 0 ⇐ lamps.length ⇐ 20000

  3. 0 ⇐ queries.length ⇐ 20000

  4. lamps[i].length == queries[i].length == 2

1
Unresolved directive in 1001-grid-illumination.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1001_GridIllumination.java[]

1002. Find Common Characters

Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.

You may return the answer in any order.

Example 1:

Input: ["bella","label","roller"]
Output: ["e","l","l"]

Example 2:

Input: ["cool","lock","cook"]
Output: ["c","o"]

Note:

  1. 1 ⇐ A.length ⇐ 100

  2. 1 ⇐ A[i].length ⇐ 100

  3. A[i][j] is a lowercase letter

1
Unresolved directive in 1002-find-common-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1002_FindCommonCharacters.java[]

1003. Check If Word Is Valid After Substitutions

We are given that the string "abc" is valid.

From any valid string V, we may split V into two pieces X and Y such that X + Y (X concatenated with Y) is equal to V. (X or Y may be empty.) Then, X + "abc" + Y is also valid.

If for example S = "abc", then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc". Examples of invalid strings are: "abccba", "ab", "cababc", "bac".

Return true if and only if the given string S is valid.

Example 1:

Input: "aabcbc"
Output: true
Explanation:
We start with the valid string "abc".
Then we can insert another "abc" between "a" and "bc", resulting in "a" + "abc" + "bc" which is "aabcbc".

Example 2:

Input: "abcabcababcc"
Output: true
Explanation:
"abcabcabc" is valid after consecutive insertings of "abc".
Then we can insert "abc" before the last letter, resulting in "abcabcab" + "abc" + "c" which is "abcabcababcc".

Example 3:

Input: "abccba"
Output: false

Example 4:

Input: "cababc"
Output: false

Note:

  1. 1 ⇐ S.length ⇐ 20000

  2. S[i] is 'a', 'b', or 'c'

1
Unresolved directive in 1003-check-if-word-is-valid-after-substitutions.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1003_CheckIfWordIsValidAfterSubstitutions.java[]

1004. Max Consecutive Ones III

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:

Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,[.underline]1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Example 2:

Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,[.underline]1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Note:

  1. 1 ⇐ A.length ⇐ 20000

  2. 0 ⇐ K ⇐ A.length

  3. A[i] is 0 or 1

1
Unresolved directive in 1004-max-consecutive-ones-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1004_MaxConsecutiveOnesIII.java[]

1005. Maximize Sum Of Array After K Negations

Given an array A of integers, we must modify the array in the following way: we choose an i and replace A[i] with -A[i], and we repeat this process K times in total. (We may choose the same index i multiple times.)

Return the largest possible sum of the array after modifying it in this way.

Example 1:

Input: A = [4,2,3], K = 1
Output: 5
Explanation: Choose indices (1,) and A becomes [4,-2,3].

Example 2:

Input: A = [3,-1,0,2], K = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2].

Example 3:

Input: A = [2,-3,-1,5,-4], K = 2
Output: 13
Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4].

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. 1 ⇐ K ⇐ 10000

  3. -100 ⇐ A[i] ⇐ 100

1
Unresolved directive in 1005-maximize-sum-of-array-after-k-negations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1005_MaximizeSumOfArrayAfterKNegations.java[]

1006. Clumsy Factorial

Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.

For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.

<font face="sans-serif, Arial, Verdana, Trebuchet MS">Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.

Example 1:

Input: 4
Output: 7
Explanation: 7 = 4 * 3 / 2 + 1

Example 2:

Input: 10
Output: 12
Explanation: 12 = 10  9 / 8 + 7 - 6  5 / 4 + 3 - 2 * 1

Note:

  1. 1 ⇐ N ⇐ 10000

  2. -2^31 ⇐ answer ⇐ 2^31 - 1 (The answer is guaranteed to fit within a 32-bit integer.)

1
Unresolved directive in 1006-clumsy-factorial.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1006_ClumsyFactorial.java[]

1007. Minimum Domino Rotations For Equal Row

In a row of dominoes, A[i] and B[i] represent the top and bottom halves of the i-th domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)

We may rotate the i-th domino, so that A[i] and B[i] swap values.

Return the minimum number of rotations so that all the values in A are the same, or all the values in B are the same.

If it cannot be done, return -1.

Example 1:

domino
Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2]
Output: 2
Explanation:
The first figure represents the dominoes as given by A and B: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.

Example 2:

Input: A = [3,5,1,2,3], B = [3,6,3,3,4]
Output: -1
Explanation:
In this case, it is not possible to rotate the dominoes to make one row of values equal.

Note:

  1. 1 ⇐ A[i], B[i] ⇐ 6

  2. 2 ⇐ A.length == B.length ⇐ 20000

1
Unresolved directive in 1007-minimum-domino-rotations-for-equal-row.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1007_MinimumDominoRotationsForEqualRow.java[]

1008. Construct Binary Search Tree from Preorder Traversal

Return the root node of a binary search tree that matches the given preorder traversal.

(Recall that a binary search tree is a binary tree where for every <font face="monospace">node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

:https://assets.leetcode.com/uploads/2019/03/06/1266.png" alt="1266">

Note:

  1. 1 ⇐ preorder.length ⇐ 100

  2. The values of preorder are distinct.

1
Unresolved directive in 1008-construct-binary-search-tree-from-preorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1008_ConstructBinarySearchTreeFromPreorderTraversal.java[]

1009. Complement of Base 10 Integer

Every non-negative integer N has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for N = 0, there are no leading zeroes in any binary representation.

The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary.

For a given number N in base-10, return the complement of it’s binary representation as a base-10 integer.

Example 1:

Input: 5
Output: 2
Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.

Example 2:

Input: 7
Output: 0
Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.

Example 3:

Input: 10
Output: 5
Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.

Note:

  1. 0 ⇐ N < 10^9

1
Unresolved directive in 1009-complement-of-base-10-integer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1009_ComplementOfBase10Integer.java[]

1010. Pairs of Songs With Total Durations Divisible by 60

In a list of songs, the i-th song has a duration of time[i] seconds.

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i < j with (time[i] + time[j]) % 60 == 0.

Example 1:

Input: [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60

Example 2:

Input: [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.

Note:

  1. 1 ⇐ time.length ⇐ 60000

  2. 1 ⇐ time[i] ⇐ 500

1
Unresolved directive in 1010-pairs-of-songs-with-total-durations-divisible-by-60.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1010_PairsOfSongsWithTotalDurationsDivisibleBy60.java[]

1011. Capacity To Ship Packages Within D Days

A conveyor belt has packages that must be shipped from one port to another within D days.

The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days.

Example 1:

Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10

Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.

Example 2:

Input: weights = [3,2,2,4,1,4], D = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4

Example 3:

Input: weights = [1,2,3,1,1], D = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1

Note:

  1. 1 ⇐ D ⇐ weights.length ⇐ 50000

  2. 1 ⇐ weights[i] ⇐ 500

1
Unresolved directive in 1011-capacity-to-ship-packages-within-d-days.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1011_CapacityToShipPackagesWithinDDays.java[]

1012. Numbers With Repeated Digits

Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.

Example 1:

Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.

Example 2:

Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.

Example 3:

Input: 1000
Output: 262

Note:

  1. 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 1012-numbers-with-repeated-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1012_NumbersWithRepeatedDigits.java[]

1013. Partition Array Into Three Parts With Equal Sum

Given an array A of integers, return true if and only if we can partition the array into three non-empty parts with equal sums.

Formally, we can partition the array if we can find indexes i+1 < j with (A[0] + A[1] + …​ + A[i] == A[i+1] + A[i+2] + …​ + A[j-1] == A[j] + A[j-1] + …​ + A[A.length - 1])

Example 1:

Input: [0,2,1,-6,6,-7,9,1,2,0,1]
Output: true
Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1

Example 2:

Input: [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:

Input: [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Note:

  1. 3 ⇐ A.length ⇐ 50000

  2. -10000 ⇐ A[i] ⇐ 10000

1
Unresolved directive in 1013-partition-array-into-three-parts-with-equal-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1013_PartitionArrayIntoThreePartsWithEqualSum.java[]

1014. Best Sightseeing Pair

Given an array A of positive integers, A[i] represents the value of the i-th sightseeing spot, and two sightseeing spots i and j have distance j - i between them.

The score of a pair (i < j) of sightseeing spots is (A[i] + A[j] + i - j) : the sum of the values of the sightseeing spots, minus the distance between them.

Return the maximum score of a pair of sightseeing spots.

Example 1:

Input: [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11

Note:

  1. 2 ⇐ A.length ⇐ 50000

  2. 1 ⇐ A[i] ⇐ 1000

1
Unresolved directive in 1014-best-sightseeing-pair.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1014_BestSightseeingPair.java[]

1015. Smallest Integer Divisible by K

Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1.

Return the length of N. If there is no such N, return -1.

Example 1:

Input: 1
Output: 1
Explanation: The smallest answer is N = 1, which has length 1.

Example 2:

Input: 2
Output: -1
Explanation: There is no such positive integer N divisible by 2.

Example 3:

Input: 3
Output: 3
Explanation: The smallest answer is N = 111, which has length 3.

Note:

  • 1 ⇐ K ⇐ 10^5

1
Unresolved directive in 1015-smallest-integer-divisible-by-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1015_SmallestIntegerDivisibleByK.java[]

1016. Binary String With Substrings Representing 1 To N

Given a binary string S (a string consisting only of '0' and '1’s) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.

Example 1:

Input: S = "0110", N = 3
Output: true

Example 2:

Input: S = "0110", N = 4
Output: false

Note:

  1. 1 ⇐ S.length ⇐ 1000

  2. 1 ⇐ N ⇐ 10^9

1
Unresolved directive in 1016-binary-string-with-substrings-representing-1-to-n.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1016_BinaryStringWithSubstringsRepresenting1ToN.java[]

1017. Convert to Base -2

Given a number N, return a string consisting of "0"`s and `"1"`s that represents its value in base `-2 (negative two).

The returned string must have no leading zeroes, unless the string is "0".

Example 1:

Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2

Example 2:

Input: 3
Output: "111"
Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3

Example 3:

Input: 4
Output: "100"
Explantion: (-2) ^ 2 = 4

Note:

  1. 0 ⇐ N ⇐ 10^9

1
Unresolved directive in 1017-convert-to-base-2.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1017_ConvertToBase2.java[]

1018. Binary Prefix Divisible By 5

Given an array A of 0`s and `1`s, consider `N_i: the i-th subarray from A[0] to A[i] interpreted as a binary number (from most-significant-bit to least-significant-bit.)

Return a list of booleans answer, where answer[i] is true if and only if N_i is divisible by 5.

Example 1:

Input: [0,1,1]
Output: [true,false,false]
Explanation:
The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.  Only the first number is divisible by 5, so answer[0] is true.

Example 2:

Input: [1,1,1]
Output: [false,false,false]

Example 3:

Input: [0,1,1,1,1,1]
Output: [true,false,false,false,true,false]

Example 4:

Input: [1,1,1,0,1]
Output: [false,false,false,false,false]

Note:

  1. 1 ⇐ A.length ⇐ 30000

  2. A[i] is 0 or 1

1
Unresolved directive in 1018-binary-prefix-divisible-by-5.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1018_BinaryPrefixDivisibleBy5.java[]

1019. Next Greater Node In Linked List

We are given a linked list with head as the first node. Let’s number the nodes in the list: node_1, node_2, node_3, …​ etc.

Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0.

Return an array of integers answer, where answer[i] = next_larger(node_{i+1}).

Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.

Example 1:

Input: [2,1,5]
Output: [5,5,0]

Example 2:

Input: [2,7,4,3,5]
Output: [7,0,5,5,0]

Example 3:

Input: [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]

Note:

  1. 1 ⇐ node.val ⇐ 10^9 for each node in the linked list.

  2. The given list has length in the range [0, 10000].

1
Unresolved directive in 1019-next-greater-node-in-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1019_NextGreaterNodeInLinkedList.java[]

1020. Number of Enclaves

Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)

A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.

Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.

Example 1:

Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.

Example 2:

Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation:
All 1s are either on the boundary or can reach the boundary.

Note:

  1. 1 ⇐ A.length ⇐ 500

  2. 1 ⇐ A[i].length ⇐ 500

  3. 0 ⇐ A[i][j] ⇐ 1

  4. All rows have the same size.

1
Unresolved directive in 1020-number-of-enclaves.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1020_NumberOfEnclaves.java[]

1021. Remove Outermost Parentheses

A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "))()", and "(()(()" are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + …​ + P_k, where P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: ")())" Output: "()()()" Explanation: The input string is "(()())", with primitive decomposition "(()(" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: ")())(()(()"
Output: "()()()()))" Explanation: The input string is "(()())(()(()", with primitive decomposition ")(" + "))" + "(()(()".
After removing outer parentheses of each part, this is "()()" + "()" + "()))" = "()()()()((".

Example 3:

Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

Note:

  1. S.length ⇐ 10000

  2. S[i] is "(" or ")"

  3. S is a valid parentheses string

1
Unresolved directive in 1021-remove-outermost-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1021_RemoveOutermostParentheses.java[]

1022. Sum of Root To Leaf Binary Numbers

Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 → 1 → 1 → 0 → 1, then this could represent 01101 in binary, which is 13.

For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.

Return the sum of these numbers.

Example 1:

sum of root to leaf binary numbers
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22

Note:

  1. The number of nodes in the tree is between 1 and 1000.

  2. node.val is 0 or 1.

  3. The answer will not exceed 2^31 - 1.

1
Unresolved directive in 1022-sum-of-root-to-leaf-binary-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1022_SumOfRootToLeafBinaryNumbers.java[]

1023. Camelcase Matching

A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.)

Given a list of queries, and a pattern, return an answer list of booleans, where answer[i] is true if and only if queries[i] matches the pattern.

Example 1:

Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
Output: [true,false,true,true,false]
Explanation:
"FooBar" can be generated like this "F" + "oo" + "B" + "ar".
"FootBall" can be generated like this "F" + "oot" + "B" + "all".
"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".

Example 2:

Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
Output: [true,false,true,false,false]
Explanation:
"FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".
"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".

Example 3:

Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
Output: [false,true,false,false,false]
Explanation:
"FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".

Note:

  1. 1 ⇐ queries.length ⇐ 100

  2. 1 ⇐ queries[i].length ⇐ 100

  3. 1 ⇐ pattern.length ⇐ 100

  4. All strings consists only of lower and upper case English letters.

1
Unresolved directive in 1023-camelcase-matching.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1023_CamelcaseMatching.java[]

1024. Video Stitching

You are given a series of video clips from a sporting event that lasted T seconds. These video clips can be overlapping with each other and have varied lengths.

Each video clip clips[i] is an interval: it starts at time clips[i][0] and ends at time clips[i][1]. We can cut these clips into segments freely: for example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].

Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event ([0, T]). If the task is impossible, return -1.

Example 1:

Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], T = 10
Output: 3
Explanation:
We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut [1,9] into segments [1,2] + [2,8] + [8,9].
Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].

Example 2:

Input: clips = [[0,1],[1,2]], T = 5
Output: -1
Explanation:
We can't cover [0,5] with only [0,1] and [0,2].

Example 3:

Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], T = 9
Output: 3
Explanation:
We can take clips [0,4], [4,7], and [6,9].

Example 4:

Input: clips = [[0,4],[2,8]], T = 5
Output: 2
Explanation:
Notice you can have extra video after the event ends.

Note:

  1. 1 ⇐ clips.length ⇐ 100

  2. 0 ⇐ clips[i][0], clips[i][1] ⇐ 100

  3. 0 ⇐ T ⇐ 100

1
Unresolved directive in 1024-video-stitching.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1024_VideoStitching.java[]

1025. Divisor Game

Alice and Bob take turns playing a game, with Alice starting first.

Initially, there is a number N on the chalkboard. On each player’s turn, that player makes a move consisting of:

  • Choosing any x with 0 < x < N and N % x == 0.

  • Replacing the number N on the chalkboard with N - x.

Also, if a player cannot make a move, they lose the game.

Return True if and only if Alice wins the game, assuming both players play optimally.

Example 1:

Input: 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.

Example 2:

Input: 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.

Note:

  • 1 ⇐ N ⇐ 1000

1
Unresolved directive in 1025-divisor-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1025_DivisorGame.java[]

1026. Maximum Difference Between Node and Ancestor

Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.

(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

Example 1:

2whqcep
Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation:
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

Note:

  1. The number of nodes in the tree is between 2 and 5000.

  2. Each node will have value between 0 and 100000.

1
Unresolved directive in 1026-maximum-difference-between-node-and-ancestor.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1026_MaximumDifferenceBetweenNodeAndAncestor.java[]

1027. Longest Arithmetic Sequence

Given an array A of integers, return the length of the longest arithmetic subsequence in A.

Recall that a subsequence of A is a list A[i_1], A[i_2], …​, A[i_k] with 0 ⇐ i_1 < i_2 < …​ < i_k ⇐ A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 ⇐ i < B.length - 1).

Example 1:

Input: [3,6,9,12]
Output: 4
Explanation:
The whole array is an arithmetic sequence with steps of length = 3.

Example 2:

Input: [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].

Example 3:

Input: [20,1,15,3,10,5,8]
Output: 4
Explanation:
The longest arithmetic subsequence is [20,15,10,5].

Note:

  1. 2 ⇐ A.length ⇐ 2000

  2. 0 ⇐ A[i] ⇐ 10000

1
Unresolved directive in 1027-longest-arithmetic-sequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1027_LongestArithmeticSequence.java[]

1028. Recover a Tree From Preorder Traversal

We run a preorder depth first search on the root of a binary tree.

At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. (If the depth of a node is D, the depth of its immediate child is D+1. The depth of the root node is 0.)

If a node has only one child, that child is guaranteed to be the left child.

Given the output S of this traversal, recover the tree and return its root.

Example 1:

recover a tree from preorder traversal
Input: "1-2--3--4-5--6--7"
Output: [1,2,5,3,4,6,7]

Example 2:

screen shot 2019 04 10 at 114101 pm
Input: "1-2--3---4-5--6---7"
Output: [1,2,5,3,null,6,null,4,null,7]

Example 3:

screen shot 2019 04 10 at 114955 pm
Input: "1-401--349---90--88"
Output: [1,401,null,349,88,90]

Note:

  • The number of nodes in the original tree is between 1 and 1000.

  • Each node will have a value between 1 and 10^9.

1
Unresolved directive in 1028-recover-a-tree-from-preorder-traversal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1028_RecoverATreeFromPreorderTraversal.java[]

1029. Two City Scheduling

There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].

Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.

Example 1:

Input: [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation:
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Note:

  1. 1 ⇐ costs.length ⇐ 100

  2. It is guaranteed that costs.length is even.

  3. 1 ⇐ costs[i][0], costs[i][1] ⇐ 1000

1
Unresolved directive in 1029-two-city-scheduling.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1029_TwoCityScheduling.java[]

1030. Matrix Cells in Distance Order

We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 ⇐ r < R and 0 ⇐ c < C.

Additionally, we are given a cell in that matrix with coordinates (r0, c0).

Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0) from smallest distance to largest distance. Here, the distance between two cells (r1, c1) and (r2, c2) is the Manhattan distance, |r1 - r2| + |c1 - c2|. (You may return the answer in any order that satisfies this condition.)

Example 1:

Input: R = 1, C = 2, r0 = 0, c0 = 0
Output: [[0,0],[0,1]]
Explanation: The distances from (r0, c0) to other cells are: [0,1]

Example 2:

Input: R = 2, C = 2, r0 = 0, c0 = 1
Output: [[0,1],[0,0],[1,1],[1,0]]
Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2]
The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.

Example 3:

Input: R = 2, C = 3, r0 = 1, c0 = 2
Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3]
There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].

Note:

  1. 1 ⇐ R ⇐ 100

  2. 1 ⇐ C ⇐ 100

  3. 0 ⇐ r0 < R

  4. 0 ⇐ c0 < C

1
Unresolved directive in 1030-matrix-cells-in-distance-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1030_MatrixCellsInDistanceOrder.java[]

1031. Maximum Sum of Two Non-Overlapping Subarrays

Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M. (For clarification, the L-length subarray could occur before or after the M-length subarray.)

Formally, return the largest V for which V = (A[i] + A[i+1] + …​ + A[i+L-1]) + (A[j] + A[j+1] + …​ + A[j+M-1]) and either:

  • 0 ⇐ i < i + L - 1 < j < j + M - 1 < A.length, or

  • 0 ⇐ j < j + M - 1 < i < i + L - 1 < A.length.

Example 1:

Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.

Example 2:

Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.

Example 3:

Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.

Note:

  • L >= 1

  • M >= 1

  • L + M ⇐ A.length ⇐ 1000

  • 0 ⇐ A[i] ⇐ 1000

1
Unresolved directive in 1031-maximum-sum-of-two-non-overlapping-subarrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1031_MaximumSumOfTwoNonOverlappingSubarrays.java[]

1032. Stream of Characters

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:

StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // init the dictionary.
streamChecker.query('a');          // return false
streamChecker.query('b');          // return false
streamChecker.query('c');          // return false
streamChecker.query('d');          // return true, because 'cd' is in the wordlist
streamChecker.query('e');          // return false
streamChecker.query('f');          // return true, because 'f' is in the wordlist
streamChecker.query('g');          // return false
streamChecker.query('h');          // return false
streamChecker.query('i');          // return false
streamChecker.query('j');          // return false
streamChecker.query('k');          // return false
streamChecker.query('l');          // return true, because 'kl' is in the wordlist

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.

1
Unresolved directive in 1032-stream-of-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1032_StreamOfCharacters.java[]

1033. Moving Stones Until Consecutive

Three stones are on a number line at positions a, b, and c.

Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let’s say the stones are currently at positions x, y, z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.

The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

When the game ends, what is the minimum and maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

Example 1:

Input: a = 1, b = 2, c = 5
Output: [1,2]
Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

Example 2:

Input: a = 4, b = 3, c = 2
Output: [0,0]
Explanation: We cannot make any moves.

Example 3:

Input: a = 3, b = 5, c = 1
Output: [1,2]
Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.

Note:

  1. 1 ⇐ a ⇐ 100

  2. 1 ⇐ b ⇐ 100

  3. 1 ⇐ c ⇐ 100

  4. a != b, b != c, c != a

1
Unresolved directive in 1033-moving-stones-until-consecutive.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1033_MovingStonesUntilConsecutive.java[]

1034. Coloring A Border

Given a 2-dimensional grid of integers, each value in the grid represents the color of the grid square at that location.

Two squares belong to the same connected component if and only if they have the same color and are next to each other in any of the 4 directions.

The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).

Given a square at location (r0, c0) in the grid and a color, color the border of the connected component of that square with the given color, and return the final grid.

Example 1:

Input: grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
Output: [[3, 3], [3, 2]]

Example 2:

Input: grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
Output: [[1, 3, 3], [2, 3, 3]]

Example 3:

Input: grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
Output: [[2, 2, 2], [2, 1, 2], [2, 2, 2]]

Note:

  1. 1 ⇐ grid.length ⇐ 50

  2. 1 ⇐ grid[0].length ⇐ 50

  3. 1 ⇐ grid[i][j] ⇐ 1000

  4. 0 ⇐ r0 < grid.length

  5. 0 ⇐ c0 < grid[0].length

  6. 1 ⇐ color ⇐ 1000

1
Unresolved directive in 1034-coloring-a-border.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1034_ColoringABorder.java[]

1035. Uncrossed Lines

We write the integers of A and B (in the order they are given) on two separate horizontal lines.

Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:

  • A[i] == B[j];

  • The line we draw does not intersect any other connecting (non-horizontal) line.

Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.

Return the maximum number of connecting lines we can draw in this way.

Example 1:

142
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.

Example 2:

Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3

Example 3:

Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2

Note:

  • 1 ⇐ A.length ⇐ 500

  • 1 ⇐ B.length ⇐ 500

  • <font face="monospace">1 ⇐ A[i], B[i] ⇐ 2000

1
Unresolved directive in 1035-uncrossed-lines.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1035_UncrossedLines.java[]

1036. Escape a Large Maze

In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 ⇐ x, y < 10^6.

We start at the source square and want to reach the target square. Each move, we can walk to a 4-directionally adjacent square in the grid that isn’t in the given list of blocked squares.

Return true if and only if it is possible to reach the target square through a sequence of moves.

Example 1:

Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
Explanation:
The target square is inaccessible starting from the source square, because we can't walk outside the grid.

Example 2:

Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
Explanation:
Because there are no blocked cells, it's possible to reach the target square.

Note:

  1. 0 ⇐ blocked.length ⇐ 200

  2. blocked[i].length == 2

  3. 0 ⇐ blocked[i][j] < 10^6

  4. source.length == target.length == 2

  5. 0 ⇐ source[i][j], target[i][j] < 10^6

  6. source != target

1
Unresolved directive in 1036-escape-a-large-maze.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1036_EscapeALargeMaze.java[]

1037. Valid Boomerang

A boomerang is a set of 3 points that are all distinct and not in a straight line.

Given a list of three points in the plane, return whether these points are a boomerang.

Example 1:

Input: [[1,1],[2,3],[3,2]]
Output: true

Example 2:

Input: [[1,1],[2,2],[3,3]]
Output: false

Note:

  1. points.length == 3

  2. points[i].length == 2

  3. 0 ⇐ points[i][j] ⇐ 100

1
Unresolved directive in 1037-valid-boomerang.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1037_ValidBoomerang.java[]

1038. Binary Search Tree to Greater Sum Tree

Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.

As a reminder, a binary search tree is a tree that satisfies these constraints:

  • The left subtree of a node contains only nodes with keys less than the node’s key.

  • The right subtree of a node contains only nodes with keys greater than the node’s key.

  • Both the left and right subtrees must also be binary search trees.

Example 1:

tree
Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Note:

  • The number of nodes in the tree is between 1 and 100.

  • Each node will have value between 0 and 100.

  • The given tree is a binary search tree.

1
Unresolved directive in 1038-binary-search-tree-to-greater-sum-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1038_BinarySearchTreeToGreaterSumTree.java[]

1039. Minimum Score Triangulation of Polygon

Given N, consider a convex N-sided polygon with vertices labelled A[0], A[i], …​, A[N-1] in clockwise order.

Suppose you triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation is the sum of these values over all N-2 triangles in the triangulation.

Return the smallest possible total score that you can achieve with some triangulation of the polygon.

Example 1:

Input: [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.

Example 2:

minimum score triangulation of polygon 1
Input: [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 375 + 457 = 245, or 345 + 347 = 144.  The minimum score is 144.

Example 3:

Input: [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 113 + 114 + 115 + 111 = 13.

Note:

  1. 3 ⇐ A.length ⇐ 50

  2. 1 ⇐ A[i] ⇐ 100

1
Unresolved directive in 1039-minimum-score-triangulation-of-polygon.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1039_MinimumScoreTriangulationOfPolygon.java[]

1040. Moving Stones Until Consecutive II

On an infinite number line, the position of the i-th stone is given by stones[i]. Call a stone an endpoint stone if it has the smallest or largest position.

Each turn, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.

The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

When the game ends, what is the minimum and maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

Example 1:

Input: [7,4,9]
Output: [1,2]
Explanation:
We can move 4 -> 8 for one move to finish the game.
Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.

Example 2:

Input: [6,5,4,3,10]
Output: [2,3]
We can move 3 -> 8 then 10 -> 7 to finish the game.
Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.
Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.

Example 3:

Input: [100,101,104,102,103]
Output: [0,0]

Note:

  1. 3 ⇐ stones.length ⇐ 10^4

  2. 1 ⇐ stones[i] ⇐ 10^9

  3. stones[i] have distinct values.

1
Unresolved directive in 1040-moving-stones-until-consecutive-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1040_MovingStonesUntilConsecutiveII.java[]

1041. Robot Bounded In Circle

On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:

  • "G": go straight 1 unit;

  • "L": turn 90 degrees to the left;

  • "R": turn 90 degress to the right.

The robot performs the instructions given in order, and repeats them forever.

Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

Example 1:

Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.

Example 2:

Input: "GG"
Output: false
Explanation:
The robot moves north indefinitely.

Example 3:

Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...

Note:

  • 1 ⇐ instructions.length ⇐ 100

  • instructions[i] is in {'G', 'L', 'R'}

1
Unresolved directive in 1041-robot-bounded-in-circle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1041_RobotBoundedInCircle.java[]

1042. Flower Planting With No Adjacent

You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.

paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.

Also, there is no garden that has more than 3 paths coming into or leaving it.

Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.

Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)-th garden. The flower types are denoted <font face="monospace">1, <font face="monospace">2, <font face="monospace">3, or <font face="monospace">4. It is guaranteed an answer exists.

Example 1:

Input: N = 3, paths = [[1,2],[2,3],[3,1]]
Output: [1,2,3]

Example 2:

Input: N = 4, paths = [[1,2],[3,4]]
Output: [1,2,1,2]

Example 3:

Input: N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Output: [1,2,3,4]

Note:

  • 1 ⇐ N ⇐ 10000

  • 0 ⇐ paths.size ⇐ 20000

  • No garden has 4 or more paths coming into or leaving it.

  • It is guaranteed an answer exists.

1
Unresolved directive in 1042-flower-planting-with-no-adjacent.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1042_FlowerPlantingWithNoAdjacent.java[]

1043. Partition Array for Maximum Sum

Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.

Return the largest sum of the given array after partitioning.

Example 1:

Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]

Note:

  1. 1 ⇐ K ⇐ A.length ⇐ 500

  2. 0 ⇐ A[i] ⇐ 10^6

1
Unresolved directive in 1043-partition-array-for-maximum-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1043_PartitionArrayForMaximumSum.java[]

1044. Longest Duplicate Substring

Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)

Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".)

Example 1:

Input: "banana"
Output: "ana"

Example 2:

Input: "abcd"
Output: ""

Note:

  1. 2 ⇐ S.length ⇐ 10^5

  2. S consists of lowercase English letters.

1
Unresolved directive in 1044-longest-duplicate-substring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1044_LongestDuplicateSubstring.java[]

1045. Customers Who Bought All Products

1
Unresolved directive in 1045-customers-who-bought-all-products.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1045_CustomersWhoBoughtAllProducts.java[]

1046. Last Stone Weight

We have a collection of rocks, each rock has a positive integer weight.

Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x ⇐ y. The result of this smash is:

  • If x == y, both stones are totally destroyed;

  • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)

Example 1:

Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.

Note:

  • 1 ⇐ stones.length ⇐ 30

  • 1 ⇐ stones[i] ⇐ 1000

1
Unresolved directive in 1046-last-stone-weight.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1046_LastStoneWeight.java[]

1047. Remove All Adjacent Duplicates In String

Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.

Example 1:

Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

  1. 1 ⇐ S.length ⇐ 20000

  2. S consists only of English lowercase letters.

1
Unresolved directive in 1047-remove-all-adjacent-duplicates-in-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1047_RemoveAllAdjacentDuplicatesInString.java[]

1048. Longest String Chain

Given a list of words, each word consists of English lowercase letters.

Let’s say word1 is a predecessor of word2 if and only if we can add exactly one letter anywhere in word1 to make it equal to word2. For example, "abc" is a predecessor of "abac".

A _word chain _is a sequence of words [word_1, word_2, …​, word_k] with k >= 1, where word_1 is a predecessor of word_2, word_2 is a predecessor of word_3, and so on.

Return the longest possible length of a word chain with words chosen from the given list of words.

Example 1:

Input: ["a","b","ba","bca","bda","bdca"]
Output: 4
Explanation: one of the longest word chain is "a","ba","bda","bdca".

Note:

  1. 1 ⇐ words.length ⇐ 1000

  2. 1 ⇐ words[i].length ⇐ 16

  3. words[i] only consists of English lowercase letters.

1
Unresolved directive in 1048-longest-string-chain.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1048_LongestStringChain.java[]

1049. Last Stone Weight II

We have a collection of rocks, each rock has a positive integer weight.

Each turn, we choose any two rocks and smash them together. Suppose the stones have weights x and y with x ⇐ y. The result of this smash is:

  • If x == y, both stones are totally destroyed;

  • If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x.

At the end, there is at most 1 stone left. Return the smallest possible weight of this stone (the weight is 0 if there are no stones left.)

Example 1:

Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2 so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1 so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0 so the array converts to [1] then that's the optimal value.

Note:

  • 1 ⇐ stones.length ⇐ 30

  • 1 ⇐ stones[i] ⇐ 100

1
Unresolved directive in 1049-last-stone-weight-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1049_LastStoneWeightII.java[]

1050. Actors and Directors Who Cooperated At Least Three Times

1
Unresolved directive in 1050-actors-and-directors-who-cooperated-at-least-three-times.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1050_ActorsAndDirectorsWhoCooperatedAtLeastThreeTimes.java[]

1051. Height Checker

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Example 1:

Input: heights = [1,1,4,2,1,3]
Output: 3

Constraints:

  • 1 ⇐ heights.length ⇐ 100

  • 1 ⇐ heights[i] ⇐ 100

1
Unresolved directive in 1051-height-checker.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1051_HeightChecker.java[]

1052. Grumpy Bookstore Owner

Today, the bookstore owner has a store open for customers.length minutes. Every minute, some number of customers (customers[i]) enter the store, and all those customers leave after the end of that minute.

On some minutes, the bookstore owner is grumpy. If the bookstore owner is grumpy on the i-th minute, grumpy[i] = 1, otherwise grumpy[i] = 0. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise they are satisfied.

The bookstore owner knows a secret technique to keep themselves not grumpy for X minutes straight, but can only use it once.

Return the maximum number of customers that can be satisfied throughout the day.

Example 1:

Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3
Output: 16
Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes.
The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.

Note:

  • 1 ⇐ X ⇐ customers.length == grumpy.length ⇐ 20000

  • 0 ⇐ customers[i] ⇐ 1000

  • 0 ⇐ grumpy[i] ⇐ 1

1
Unresolved directive in 1052-grumpy-bookstore-owner.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1052_GrumpyBookstoreOwner.java[]

1053. Previous Permutation With One Swap

Given an array A of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A, that can be made with one swap (A swap exchanges the positions of two numbers A[i] and A[j]). If it cannot be done, then return the same array.

Example 1:

Input: [3,2,1]
Output: [3,1,2]
Explanation: Swapping 2 and 1.

Example 2:

Input: [1,1,5]
Output: [1,1,5]
Explanation: This is already the smallest permutation.

Example 3:

Input: [1,9,4,6,7]
Output: [1,7,4,6,9]
Explanation: Swapping 9 and 7.

Example 4:

Input: [3,1,1,3]
Output: [1,3,1,3]
Explanation: Swapping 1 and 3.

Note:

  1. 1 ⇐ A.length ⇐ 10000

  2. 1 ⇐ A[i] ⇐ 10000

1
Unresolved directive in 1053-previous-permutation-with-one-swap.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1053_PreviousPermutationWithOneSwap.java[]

1054. Distant Barcodes

In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].

Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.

Example 1:

Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]

Example 2:

Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]

Note:

  1. 1 ⇐ barcodes.length ⇐ 10000

  2. 1 ⇐ barcodes[i] ⇐ 10000

1
Unresolved directive in 1054-distant-barcodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1054_DistantBarcodes.java[]

1055. Shortest Way to Form String

1
Unresolved directive in 1055-shortest-way-to-form-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1055_ShortestWayToFormString.java[]

1056. Confusing Number

1
Unresolved directive in 1056-confusing-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1056_ConfusingNumber.java[]

1057. Campus Bikes

1
Unresolved directive in 1057-campus-bikes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1057_CampusBikes.java[]

1058. Minimize Rounding Error to Meet Target

1
Unresolved directive in 1058-minimize-rounding-error-to-meet-target.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1058_MinimizeRoundingErrorToMeetTarget.java[]

1059. All Paths from Source Lead to Destination

1
Unresolved directive in 1059-all-paths-from-source-lead-to-destination.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1059_AllPathsFromSourceLeadToDestination.java[]

1060. Missing Element in Sorted Array

1
Unresolved directive in 1060-missing-element-in-sorted-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1060_MissingElementInSortedArray.java[]

1061. Lexicographically Smallest Equivalent String

1
Unresolved directive in 1061-lexicographically-smallest-equivalent-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1061_LexicographicallySmallestEquivalentString.java[]

1062. Longest Repeating Substring

1
Unresolved directive in 1062-longest-repeating-substring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1062_LongestRepeatingSubstring.java[]

1063. Number of Valid Subarrays

1
Unresolved directive in 1063-number-of-valid-subarrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1063_NumberOfValidSubarrays.java[]

1064. Fixed Point

1
Unresolved directive in 1064-fixed-point.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1064_FixedPoint.java[]

1065. Index Pairs of a String

1
Unresolved directive in 1065-index-pairs-of-a-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1065_IndexPairsOfAString.java[]

1066. Campus Bikes II

1
Unresolved directive in 1066-campus-bikes-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1066_CampusBikesII.java[]

1067. Digit Count in Range

1
Unresolved directive in 1067-digit-count-in-range.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1067_DigitCountInRange.java[]

1068. Product Sales Analysis I

1
Unresolved directive in 1068-product-sales-analysis-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1068_ProductSalesAnalysisI.java[]

1069. Product Sales Analysis II

1
Unresolved directive in 1069-product-sales-analysis-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1069_ProductSalesAnalysisII.java[]

1070. Product Sales Analysis III

1
Unresolved directive in 1070-product-sales-analysis-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1070_ProductSalesAnalysisIII.java[]

1071. Greatest Common Divisor of Strings

For strings S and T, we say “T` divides S” if and only if `S = T + …​ + T (T concatenated with itself 1 or more times)

Return the largest string X such that X divides <font face="monospace">str1 and X divides <font face="monospace">str2.

Example 1:

Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"

Example 2:

Input: str1 = "ABABAB", str2 = "ABAB"
Output: "AB"

Example 3:

Input: str1 = "LEET", str2 = "CODE"
Output: ""

Note:

  1. 1 ⇐ str1.length ⇐ 1000

  2. 1 ⇐ str2.length ⇐ 1000

  3. str1[i] and str2[i] are English uppercase letters.

1
Unresolved directive in 1071-greatest-common-divisor-of-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1071_GreatestCommonDivisorOfStrings.java[]

1072. Flip Columns For Maximum Number of Equal Rows

Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.

Return the maximum number of rows that have all values equal after some number of flips.

Example 1:

Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.

Example 2:

Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.

Example 3:

Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.

Note:

  1. 1 ⇐ matrix.length ⇐ 300

  2. 1 ⇐ matrix[i].length ⇐ 300

  3. All `matrix[i].length’s are equal

  4. matrix[i][j] is 0 or 1

1
Unresolved directive in 1072-flip-columns-for-maximum-number-of-equal-rows.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1072_FlipColumnsForMaximumNumberOfEqualRows.java[]

1073. Adding Two Negabinary Numbers

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

Example 1:

Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]
Output: [1,0,0,0,0]
Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.

Note:

  1. 1 ⇐ arr1.length ⇐ 1000

  2. 1 ⇐ arr2.length ⇐ 1000

  3. arr1 and arr2 have no leading zeros

  4. arr1[i] is 0 or 1

  5. arr2[i] is 0 or 1

1
Unresolved directive in 1073-adding-two-negabinary-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1073_AddingTwoNegabinaryNumbers.java[]

1074. Number of Submatrices That Sum to Target

Given a matrix, and a target, return the number of non-empty submatrices that sum to <font face="monospace">target.

A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 ⇐ x ⇐ x2 and y1 ⇐ y ⇐ y2.

Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

Example 1:

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.

Example 2:

Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.

Note:

  1. 1 ⇐ matrix.length ⇐ 300

  2. 1 ⇐ matrix[0].length ⇐ 300

  3. -1000 ⇐ matrix[i] ⇐ 1000

  4. -10^8 ⇐ target ⇐ 10^8

1
Unresolved directive in 1074-number-of-submatrices-that-sum-to-target.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1074_NumberOfSubmatricesThatSumToTarget.java[]

1075. Project Employees I

1
Unresolved directive in 1075-project-employees-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1075_ProjectEmployeesI.java[]

1076. Project Employees II

1
Unresolved directive in 1076-project-employees-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1076_ProjectEmployeesII.java[]

1077. Project Employees III

1
Unresolved directive in 1077-project-employees-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1077_ProjectEmployeesIII.java[]

1078. Occurrences After Bigram

Given words first and second, consider occurrences in some text of the form “first second third”, where second comes immediately after first, and third comes immediately after second.

For each such occurrence, add “third” to the answer, and return the answer.

Example 1:

Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]

Example 2:

Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]

Note:

  1. 1 ⇐ text.length ⇐ 1000

  2. text consists of space separated words, where each word consists of lowercase English letters.

  3. 1 ⇐ first.length, second.length ⇐ 10

  4. first and second consist of lowercase English letters.

1
Unresolved directive in 1078-occurrences-after-bigram.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1078_OccurrencesAfterBigram.java[]

1079. Letter Tile Possibilities

You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.

Example 1:

Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Example 2:

Input: "AAABBC"
Output: 188

Note:

  1. 1 ⇐ tiles.length ⇐ 7

  2. tiles consists of uppercase English letters.

1
Unresolved directive in 1079-letter-tile-possibilities.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1079_LetterTilePossibilities.java[]

1080. Insufficient Nodes in Root to Leaf Paths

Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf. (A leaf is a node with no children.)

A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.

Delete all insufficient nodes simultaneously, and return the root of the resulting binary tree.

Example 1:

:https://assets.leetcode.com/uploads/2019/06/05/insufficient-11.png" alt="insufficient 11">

Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1

:https://assets.leetcode.com/uploads/2019/06/05/insufficient-2.png" alt="insufficient 2">

Output: [1,2,3,4,null,null,7,8,9,null,14]

Example 2:

:https://assets.leetcode.com/uploads/2019/06/05/insufficient-3.png" alt="insufficient 3">

Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22

:https://assets.leetcode.com/uploads/2019/06/05/insufficient-4.png" alt="insufficient 4">

Output:* [5,4,8,11,null,17,4,7,null,null,null,5]

Example 3:

:https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83301-pm.png" alt="screen shot 2019 06 11 at 83301 pm">

Input: root = [1,2,-3,-5,null,4,null], limit = -1

:https://assets.leetcode.com/uploads/2019/06/11/screen-shot-2019-06-11-at-83517-pm.png" alt="screen shot 2019 06 11 at 83517 pm">

Output: [1,null,-3,4]

Note:

  1. The given tree will have between 1 and 5000 nodes.

  2. -10^5 ⇐ node.val ⇐ 10^5

  3. -10^9 ⇐ limit ⇐ 10^9

1
Unresolved directive in 1080-insufficient-nodes-in-root-to-leaf-paths.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1080_InsufficientNodesInRootToLeafPaths.java[]

1081. Smallest Subsequence of Distinct Characters

Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.

Example 1:

Input: "cdadabcc"
Output: "adbc"

Example 2:

Input: "abcd"
Output: "abcd"

Example 3:

Input: "ecbacba"
Output: "eacb"

Example 4:

Input: "leetcode"
Output: "letcod"

Note:

  1. 1 ⇐ text.length ⇐ 1000

  2. text consists of lowercase English letters.

1
Unresolved directive in 1081-smallest-subsequence-of-distinct-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1081_SmallestSubsequenceOfDistinctCharacters.java[]

1082. Sales Analysis I

1
Unresolved directive in 1082-sales-analysis-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1082_SalesAnalysisI.java[]

1083. Sales Analysis II

1
Unresolved directive in 1083-sales-analysis-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1083_SalesAnalysisII.java[]

1084. Sales Analysis III

1
Unresolved directive in 1084-sales-analysis-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1084_SalesAnalysisIII.java[]

1085. Sum of Digits in the Minimum Number

1
Unresolved directive in 1085-sum-of-digits-in-the-minimum-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1085_SumOfDigitsInTheMinimumNumber.java[]

1086. High Five

1
Unresolved directive in 1086-high-five.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1086_HighFive.java[]

1087. Brace Expansion

1
Unresolved directive in 1087-brace-expansion.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1087_BraceExpansion.java[]

1088. Confusing Number II

1
Unresolved directive in 1088-confusing-number-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1088_ConfusingNumberII.java[]

1089. Duplicate Zeros

Given a fixed length array arr of integers, duplicate each occurrence of zero, shifting the remaining elements to the right.

Note that elements beyond the length of the original array are not written.

Do the above modifications to the input array in place, do not return anything from your function.

Example 1:

Input: [1,0,2,3,0,4,5,0]
Output: null
Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]

Example 2:

Input: [1,2,3]
Output: null
Explanation: After calling your function, the input array is modified to: [1,2,3]

Note:

  1. 1 ⇐ arr.length ⇐ 10000

  2. 0 ⇐ arr[i] ⇐ 9

1
Unresolved directive in 1089-duplicate-zeros.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1089_DuplicateZeros.java[]

1090. Largest Values From Labels

We have a set of items: the i-th item has value values[i] and label labels[i].

Then, we choose a subset S of these items, such that:

  • |S| ⇐ num_wanted

  • For every label L, the number of items in S with label L is ⇐ use_limit.

Return the largest possible sum of the subset S.

Example 1:

Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], num_wanted = 3, use_limit = 1
Output: 9
Explanation: The subset chosen is the first, third, and fifth item.

Example 2:

Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], num_wanted = 3, use_limit = 2
Output: 12
Explanation: The subset chosen is the first, second, and third item.

Example 3:

Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 1
Output: 16
Explanation: The subset chosen is the first and fourth item.

Example 4:

Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], num_wanted = 3, use_limit = 2
Output: 24
Explanation: The subset chosen is the first, second, and fourth item.

Note:

  • 1 ⇐ values.length == labels.length ⇐ 20000

  • 0 ⇐ values[i], labels[i] ⇐ 20000

  • 1 ⇐ num_wanted, use_limit ⇐ values.length

1
Unresolved directive in 1090-largest-values-from-labels.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1090_LargestValuesFromLabels.java[]

1091. Shortest Path in Binary Matrix

In an N by N square grid, each cell is either empty (0) or blocked (1).

A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, …​, C_k such that:

  • Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)

  • C_1 is at location (0, 0) (ie. has value grid[0][0])

  • C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])

  • If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).

Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.

Example 1:

Input: [[0,1],[1,0]]

:https://assets.leetcode.com/uploads/2019/08/04/example1_1.png" alt="example1 1">

Output: 2

:https://assets.leetcode.com/uploads/2019/08/04/example1_2.png" alt="example1 2">

Example 2:

Input: [[0,0,0],[1,1,0],[1,1,0]]

:https://assets.leetcode.com/uploads/2019/08/04/example2_1.png" alt="example2 1">

Output: 4

:https://assets.leetcode.com/uploads/2019/08/04/example2_2.png" alt="example2 2">

Note:

  • 1 ⇐ grid.length == grid[0].length ⇐ 100

  • grid[r][c] is 0 or 1

1
Unresolved directive in 1091-shortest-path-in-binary-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1091_ShortestPathInBinaryMatrix.java[]

1092. Shortest Common Supersequence

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.

(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

Example 1:

Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.

Note:

  1. 1 ⇐ str1.length, str2.length ⇐ 1000

  2. str1 and str2 consist of lowercase English letters.

1
Unresolved directive in 1092-shortest-common-supersequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1092_ShortestCommonSupersequence.java[]

1093. Statistics from a Large Sample

We sampled integers between 0 and 255, and stored the results in an array count: count[k] is the number of integers we sampled equal to k.

Return the minimum, maximum, mean, median, and mode of the sample respectively, as an array of floating point numbers. The mode is guaranteed to be unique.

(Recall that the median of a sample is:

  • The middle element, if the elements of the sample were sorted and the number of elements is odd;

  • The average of the middle two elements, if the elements of the sample were sorted and the number of elements is even.)

Example 1:

Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,3.00000,2.37500,2.50000,3.00000]

Example 2:

Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: [1.00000,4.00000,2.18182,2.00000,1.00000]

Constraints:

  • count.length == 256

  • 1 ⇐ sum(count) ⇐ 10^9

  • The mode of the sample that count represents is unique.

  • Answers within 10^-5 of the true value will be accepted as correct.

1
Unresolved directive in 1093-statistics-from-a-large-sample.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1093_StatisticsFromALargeSample.java[]

1094. Car Pooling

You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)

Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle’s initial location.

Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.

Example 1:

Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:

Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true

Example 3:

Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true

Example 4:

Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true

Constraints:

  1. trips.length ⇐ 1000

  2. trips[i].length == 3

  3. 1 ⇐ trips[i][0] ⇐ 100

  4. 0 ⇐ trips[i][1] < trips[i][2] ⇐ 1000

  5. 1 ⇐ capacity ⇐ 100000

1
Unresolved directive in 1094-car-pooling.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1094_CarPooling.java[]

1095. Find in Mountain Array

(This problem is an interactive problem.)

You may recall that an array A is a mountain array if and only if:

  • A.length >= 3

  • There exists some i with 0 < i < A.length - 1 such that:

  • A[0] < A[1] < …​ A[i-1] < A[i]

  • A[i] > A[i+1] > …​ > A[A.length - 1]

Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index doesn’t exist, return -1.

You can’t access the mountain array directly. You may only access the array using a MountainArray interface:

  • MountainArray.get(k) returns the element of the array at index k (0-indexed).

  • MountainArray.length() returns the length of the array.

Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.

Example 1:

Input: array = [1,2,3,4,5,3,1], target = 3
Output: 2
Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.

Example 2:

Input: array = [0,1,2,4,2,1], target = 3
Output: -1
Explanation: 3 does not exist in the array, so we return -1.

Constraints:

  • 3 ⇐ mountain_arr.length() ⇐ 10000

  • 0 ⇐ target ⇐ 10^9

  • 0 ⇐ mountain_arr.get(index) ⇐ 10^9

1
Unresolved directive in 1095-find-in-mountain-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1095_FindInMountainArray.java[]

1096. Brace Expansion II

Under a grammar given below, strings can represent a set of lowercase words. Let’s use R(expr) to denote the set of words the expression represents.

Grammar can best be understood through simple examples:

  • Single letters represent a singleton set containing that word.

  • R("a") = {"a"}

  • R("w") = {"w"}

  • When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.

  • R("{a,b,c}") = {"a","b","c"}

  • R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)

  • When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.

  • R("{a,b}{c,d}") = {"ac","ad","bc","bd"}

  • R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}

Formally, the 3 rules for our grammar:

  • For every lowercase letter x, we have R(x) = {x}

  • For expressions e_1, e_2, …​ , e_k with k >= 2, we have R({e_1,e_2,…​}) = R(e_1) ∪ R(e_2) ∪ …​

  • For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.

Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.

Example 1:

Input: "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]

Example 2:

Input: "{{a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.

Constraints:

  • 1 ⇐ expression.length ⇐ 60

  • expression[i] consists of '{', '}', ’,'`or lowercase English letters.

  • The given expression represents a set of words based on the grammar given in the description.

1
Unresolved directive in 1096-brace-expansion-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1096_BraceExpansionII.java[]

1097. Game Play Analysis V

1
Unresolved directive in 1097-game-play-analysis-v.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1097_GamePlayAnalysisV.java[]

1098. Unpopular Books

1
Unresolved directive in 1098-unpopular-books.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1098_UnpopularBooks.java[]

1099. Two Sum Less Than K

1
Unresolved directive in 1099-two-sum-less-than-k.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1099_TwoSumLessThanK.java[]

1100. Find K-Length Substrings With No Repeated Characters

1
Unresolved directive in 1100-find-k-length-substrings-with-no-repeated-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1100_FindKLengthSubstringsWithNoRepeatedCharacters.java[]

1101. The Earliest Moment When Everyone Become Friends

1
Unresolved directive in 1101-the-earliest-moment-when-everyone-become-friends.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1101_TheEarliestMomentWhenEveryoneBecomeFriends.java[]

1102. Path With Maximum Minimum Value

1
Unresolved directive in 1102-path-with-maximum-minimum-value.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1102_PathWithMaximumMinimumValue.java[]

1103. Distribute Candies to People

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:

Input: candies = 7, num_people = 4
Output: [1,2,3,1]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0,0].
On the third turn, ans[2] += 3, and the array is [1,2,3,0].
On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].

Example 2:

Input: candies = 10, num_people = 3
Output: [5,2,3]
Explanation:
On the first turn, ans[0] += 1, and the array is [1,0,0].
On the second turn, ans[1] += 2, and the array is [1,2,0].
On the third turn, ans[2] += 3, and the array is [1,2,3].
On the fourth turn, ans[0] += 4, and the final array is [5,2,3].

Constraints:

  • 1 ⇐ candies ⇐ 10^9

  • 1 ⇐ num_people ⇐ 1000

1
Unresolved directive in 1103-distribute-candies-to-people.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1103_DistributeCandiesToPeople.java[]

1104. Path In Zigzag Labelled Binary Tree

In an infinite binary tree where every node has two children, the nodes are labelled in row order.

In the odd numbered rows (ie., the first, third, fifth,…​), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,…​), the labelling is right to left.

tree

Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

Example 1:

Input: label = 14
Output: [1,3,4,14]

Example 2:

Input: label = 26
Output: [1,2,6,10,26]

Constraints:

  • 1 ⇐ label ⇐ 10^6

1
Unresolved directive in 1104-path-in-zigzag-labelled-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1104_PathInZigzagLabelledBinaryTree.java[]

1105. Filling Bookcase Shelves

We have a sequence of books: the i-th book has thickness books[i][0] and height books[i][1].

We want to place these books in order onto bookcase shelves that have total width shelf_width.

We choose some of the books to place on this shelf (such that the sum of their thickness is ⇐ shelf_width), then build another level of shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.

Note again that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.

Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.

Example 1:

shelves
Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
Output: 6
Explanation:
The sum of the heights of the 3 shelves are 1 + 3 + 2 = 6.
Notice that book number 2 does not have to be on the first shelf.

Constraints:

  • 1 ⇐ books.length ⇐ 1000

  • 1 ⇐ books[i][0] ⇐ shelf_width ⇐ 1000

  • 1 ⇐ books[i][1] ⇐ 1000

1
Unresolved directive in 1105-filling-bookcase-shelves.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1105_FillingBookcaseShelves.java[]

1106. Parsing A Boolean Expression

Return the result of evaluating a given boolean expression, represented as a string.

An expression can either be:

  • "t", evaluating to True;

  • "f", evaluating to False;

  • "!(expr)", evaluating to the logical NOT of the inner expression expr;

  • "&(expr1,expr2,…​)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, …​;

  • "|(expr1,expr2,…​)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, …​

Example 1:

Input: expression = "!(f)"
Output: true

Example 2:

Input: expression = "|(f,t)"
Output: true

Example 3:

Input: expression = "&amp;(t,f)"
Output: false

Example 4:

Input: expression = "|(&amp;(t,f,t),!(t))"
Output: false

Constraints:

  • 1 ⇐ expression.length ⇐ 20000

  • expression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.

  • expression is a valid expression representing a boolean, as given in the description.

1
Unresolved directive in 1106-parsing-a-boolean-expression.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1106_ParsingABooleanExpression.java[]

1107. New Users Daily Count

1
Unresolved directive in 1107-new-users-daily-count.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1107_NewUsersDailyCount.java[]

1108. Defanging an IP Address

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

Example 1:

Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2:

Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

Constraints:

  • The given address is a valid IPv4 address.

1
Unresolved directive in 1108-defanging-an-ip-address.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1108_DefangingAnIPAddress.java[]

1109. Corporate Flight Bookings

There are n flights, and they are labeled from 1 to n.

We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to j inclusive.

Return an array answer of length n, representing the number of seats booked on each flight in order of their label.

Example 1:

Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5
Output: [10,55,45,25,25]

Constraints:

  • 1 ⇐ bookings.length ⇐ 20000

  • 1 ⇐ bookings[i][0] ⇐ bookings[i][1] ⇐ n ⇐ 20000

  • 1 ⇐ bookings[i][2] ⇐ 10000

1
Unresolved directive in 1109-corporate-flight-bookings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1109_CorporateFlightBookings.java[]

1110. Delete Nodes And Return Forest

Given the root of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest. You may return the result in any order.

Example 1:

screen shot 2019 07 01 at 53836 pm
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]

Constraints:

  • The number of nodes in the given tree is at most 1000.

  • Each node has a distinct value between 1 and 1000.

  • to_delete.length ⇐ 1000

  • to_delete contains distinct values between 1 and 1000.

1
Unresolved directive in 1110-delete-nodes-and-return-forest.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1110_DeleteNodesAndReturnForest.java[]

1111. Maximum Nesting Depth of Two Valid Parentheses Strings

A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and:

  • It is the empty string, or

  • It can be written as AB (A concatenated with B), where A and B are VPS’s, or

  • It can be written as (A), where A is a VPS.

We can similarly define the nesting depth depth(S) of any VPS S as follows:

  • depth("") = 0

  • depth(A + B) = max(depth(A), depth(B)), where A and B are VPS’s

  • depth("(" + A + ")") = 1 + depth(A), where A is a VPS.

For example, "", "()()", and "())(" are VPS’s (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS’s.

Given a VPS <font face="monospace">seq, split it into two disjoint subsequences A and B, such that A and B are VPS’s (and A.length + B.length = seq.length).

Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.

Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.

Example 1:

Input: seq = ")("
Output: [0,1,1,1,1,0]

Example 2:

Input: seq = "()(())()"
Output: [0,0,0,1,1,0,1,1]

Constraints:

  • 1 ⇐ seq.size ⇐ 10000

1
Unresolved directive in 1111-maximum-nesting-depth-of-two-valid-parentheses-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1111_MaximumNestingDepthOfTwoValidParenthesesStrings.java[]

1112. Highest Grade For Each Student

1
Unresolved directive in 1112-highest-grade-for-each-student.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1112_HighestGradeForEachStudent.java[]

1113. Reported Posts

1
Unresolved directive in 1113-reported-posts.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1113_ReportedPosts.java[]

1114. Print in Order

Suppose we have a class:

public class Foo {
  public void first() { print("first"); }
  public void second() { print("second"); }
  public void third() { print("third"); }
}

The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().

Example 1:

Input: [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.

Example 2:

Input: [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.

Note:

We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seems to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.

1
Unresolved directive in 1114-print-in-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1114_PrintInOrder.java[]

1115. Print FooBar Alternately

Suppose you are given the following code:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i) {
      print("bar");
    }
  }
}

The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.
1
Unresolved directive in 1115-print-foobar-alternately.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1115_PrintFooBarAlternately.java[]

1116. Print Zero Even Odd

Suppose you are given the following code:

class ZeroEvenOdd {
  public ZeroEvenOdd(int n) { ... }      // constructor
  public void zero(printNumber) { ... }  // only output 0's
  public void even(printNumber) { ... }  // only output even numbers
  public void odd(printNumber) { ... }   // only output odd numbers
}

The same instance of ZeroEvenOdd will be passed to three different threads:

  1. Thread A will call zero() which should only output 0’s.

  2. Thread B will call even() which should only ouput even numbers.

  3. Thread C will call odd() which should only output odd numbers.

Each of the threads is given a printNumber method to output an integer. Modify the given program to output the series 010203040506…​ where the length of the series must be 2_n_.

Example 1:

Input: n = 2
Output: "0102"
Explanation: There are three threads being fired asynchronously. One of them calls zero(), the other calls even(), and the last one calls odd(). "0102" is the correct output.

Example 2:

Input: n = 5
Output: "0102030405"
1
Unresolved directive in 1116-print-zero-even-odd.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1116_PrintZeroEvenOdd.java[]

1117. Building H2O

There are two kinds of threads, oxygen and hydrogen. Your goal is to group these threads to form water molecules. There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must be able to immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.

In other words:

  • If an oxygen thread arrives at the barrier when no hydrogen threads are present, it has to wait for two hydrogen threads.

  • If a hydrogen thread arrives at the barrier when no other threads are present, it has to wait for an oxygen thread and another hydrogen thread.

We don’t have to worry about matching the threads up explicitly; that is, the threads do not necessarily know which other threads they are paired up with. The key is just that threads pass the barrier in complete sets; thus, if we examine the sequence of threads that bond and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.

Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

Example 1:

Input: "HOH"
Output: "HHO"
Explanation: "HOH" and "OHH" are also valid answers.

Example 2:

Input: "OOHHHH"
Output: "HHOHHO"
Explanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.

Constraints:

  • Total length of input string will be 3_n_, where 1 ≤ n ≤ 20.

  • Total number of H will be 2_n_ in the input string.

  • Total number of O will be n in the input string.

1
Unresolved directive in 1117-building-h2o.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1117_BuildingH2O.java[]

1118. Number of Days in a Month

1
Unresolved directive in 1118-number-of-days-in-a-month.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1118_NumberOfDaysInAMonth.java[]

1119. Remove Vowels from a String

1
Unresolved directive in 1119-remove-vowels-from-a-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1119_RemoveVowelsFromAString.java[]

1120. Maximum Average Subtree

1
Unresolved directive in 1120-maximum-average-subtree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1120_MaximumAverageSubtree.java[]

1121. Divide Array Into Increasing Sequences

1
Unresolved directive in 1121-divide-array-into-increasing-sequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1121_DivideArrayIntoIncreasingSequences.java[]

1122. Relative Sort Array

Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.

Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don’t appear in arr2 should be placed at the end of arr1 in ascending order.

Example 1:

Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
Output: [2,2,2,1,4,3,3,9,6,7,19]

Constraints:

  • arr1.length, arr2.length ⇐ 1000

  • 0 ⇐ arr1[i], arr2[i] ⇐ 1000

  • Each arr2[i] is distinct.

  • Each arr2[i] is in arr1.

1
Unresolved directive in 1122-relative-sort-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1122_RelativeSortArray.java[]

1123. Lowest Common Ancestor of Deepest Leaves

Given a rooted binary tree, return the lowest common ancestor of its deepest leaves.

Recall that:

  • The node of a binary tree is a leaf if and only if it has no children

  • The depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.

  • The lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A.

Example 1:

Input: root = [1,2,3]
Output: [1,2,3]
Explanation:
The deepest leaves are the nodes with values 2 and 3.
The lowest common ancestor of these leaves is the node with value 1.
The answer returned is a TreeNode object (not an array) with serialization "[1,2,3]".

Example 2:

Input: root = [1,2,3,4]
Output: [4]

Example 3:

Input: root = [1,2,3,4,5]
Output: [2,4,5]

Constraints:

  • The given tree will have between 1 and 1000 nodes.

  • Each node of the tree will have a distinct value between 1 and 1000.

1
Unresolved directive in 1123-lowest-common-ancestor-of-deepest-leaves.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1123_LowestCommonAncestorOfDeepestLeaves.java[]

1124. Longest Well-Performing Interval

We are given hours, a list of the number of hours worked per day for a given employee.

A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.

A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.

Return the length of the longest well-performing interval.

Example 1:

Input: hours = [9,9,6,0,6,6,9]
Output: 3
Explanation: The longest well-performing interval is [9,9,6].

Constraints:

  • 1 ⇐ hours.length ⇐ 10000

  • 0 ⇐ hours[i] ⇐ 16

1
Unresolved directive in 1124-longest-well-performing-interval.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1124_LongestWellPerformingInterval.java[]

1125. Smallest Sufficient Team

In a project, you have a list of required skills req_skills, and a list of people. The i-th person people[i] contains a list of skills that person has.

Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person: for example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].

Return any sufficient team of the smallest possible size, represented by the index of each person.

You may return the answer in any order. It is guaranteed an answer exists.

Example 1:

Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
Output: [0,2]

Example 2:

Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
Output: [1,2]

Constraints:

  • 1 ⇐ req_skills.length ⇐ 16

  • 1 ⇐ people.length ⇐ 60

  • 1 ⇐ people[i].length, req_skills[i].length, people[i][j].length ⇐ 16

  • Elements of req_skills and people[i] are (respectively) distinct.

  • req_skills[i][j], people[i][j][k] are lowercase English letters.

  • Every skill in people[i] is a skill in req_skills.

  • It is guaranteed a sufficient team exists.

1
Unresolved directive in 1125-smallest-sufficient-team.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1125_SmallestSufficientTeam.java[]

1126. Active Businesses

1
Unresolved directive in 1126-active-businesses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1126_ActiveBusinesses.java[]

1127. User Purchase Platform

1
Unresolved directive in 1127-user-purchase-platform.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1127_UserPurchasePlatform.java[]

1128. Number of Equivalent Domino Pairs

Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.

Return the number of pairs (i, j) for which 0 ⇐ i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].

Example 1:

Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1

Constraints:

  • 1 ⇐ dominoes.length ⇐ 40000

  • 1 ⇐ dominoes[i][j] ⇐ 9

1
Unresolved directive in 1128-number-of-equivalent-domino-pairs.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1128_NumberOfEquivalentDominoPairs.java[]

1129. Shortest Path with Alternating Colors

Consider a directed graph, with nodes labelled 0, 1, …​, n-1. In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.

Each [i, j] in red_edges denotes a red directed edge from node i to node j. Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.

Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn’t exist).

Example 1:

Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]

Example 2:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]

Example 3:

Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]

Example 4:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]

Example 5:

Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]

Constraints:

  • 1 ⇐ n ⇐ 100

  • red_edges.length ⇐ 400

  • blue_edges.length ⇐ 400

  • red_edges[i].length == blue_edges[i].length == 2

  • 0 ⇐ red_edges[i][j], blue_edges[i][j] < n

1
Unresolved directive in 1129-shortest-path-with-alternating-colors.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1129_ShortestPathWithAlternatingColors.java[]

1130. Minimum Cost Tree From Leaf Values

Given an array arr of positive integers, consider all binary trees such that:

  • Each node has either 0 or 2 children;

  • The values of arr correspond to the values of each leaf in an in-order traversal of the tree. (Recall that a node is a leaf if and only if it has 0 children.)

  • The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree respectively.

Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.

Example 1:

Input: arr = [6,2,4]
Output: 32
Explanation:
There are two possible trees.  The first has non-leaf node sum 36, and the second has non-leaf node sum 32.

    24            24
   /  \          /  \
  12   4        6    8
 /  \               / \
6    2             2   4

Constraints:

  • 2 ⇐ arr.length ⇐ 40

  • 1 ⇐ arr[i] ⇐ 15

  • It is guaranteed that the answer fits into a 32-bit signed integer (ie. it is less than 2^31).

1
Unresolved directive in 1130-minimum-cost-tree-from-leaf-values.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1130_MinimumCostTreeFromLeafValues.java[]

1131. Maximum of Absolute Value Expression

Given two arrays of integers with equal lengths, return the maximum value of:

|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|

where the maximum is taken over all 0 ⇐ i, j < arr1.length.

Example 1:

Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output: 13

Example 2:

Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20

Constraints:

  • 2 ⇐ arr1.length == arr2.length ⇐ 40000

  • -10^6 ⇐ arr1[i], arr2[i] ⇐ 10^6

1
Unresolved directive in 1131-maximum-of-absolute-value-expression.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1131_MaximumOfAbsoluteValueExpression.java[]

1132. Reported Posts II

1
Unresolved directive in 1132-reported-posts-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1132_ReportedPostsII.java[]

1133. Largest Unique Number

1
Unresolved directive in 1133-largest-unique-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1133_LargestUniqueNumber.java[]

1134. Armstrong Number

1
Unresolved directive in 1134-armstrong-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1134_ArmstrongNumber.java[]

1135. Connecting Cities With Minimum Cost

1
Unresolved directive in 1135-connecting-cities-with-minimum-cost.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1135_ConnectingCitiesWithMinimumCost.java[]

1136. Parallel Courses

1
Unresolved directive in 1136-parallel-courses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1136_ParallelCourses.java[]

1137. N-th Tribonacci Number

The Tribonacci sequence Tn is defined as follows:

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

Example 1:

Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4

Example 2:

Input: n = 25
Output: 1389537

Constraints:

  • 0 ⇐ n ⇐ 37

  • The answer is guaranteed to fit within a 32-bit integer, ie. answer ⇐ 2^31 - 1.

1
Unresolved directive in 1137-n-th-tribonacci-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1137_NThTribonacciNumber.java[]

1138. Alphabet Board Path

On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

azboard

We may make the following moves:

  • 'U' moves our position up one row, if the position exists on the board;

  • 'D' moves our position down one row, if the position exists on the board;

  • 'L' moves our position left one column, if the position exists on the board;

  • 'R' moves our position right one column, if the position exists on the board;

  • '!' adds the character board[r][c] at our current position (r, c) to the answer.

(Here, the only positions that exist on the board are positions with letters on them.)

Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.

Example 1:

Input: target = "leet"
Output: "DDR!UURRR!!DDD!"

Example 2:

Input: target = "code"
Output: "RR!DDRR!UUL!R!"

Constraints:

  • 1 ⇐ target.length ⇐ 100

  • target consists only of English lowercase letters.

1
Unresolved directive in 1138-alphabet-board-path.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1138_AlphabetBoardPath.java[]

1139. Largest 1-Bordered Square

Given a 2D grid of 0`s and `1`s, return the number of elements in the largest square subgrid that has all `1`s on its border, or `0 if such a subgrid doesn’t exist in the grid.

Example 1:

Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9

Example 2:

Input: grid = [[1,1,0,0]]
Output: 1

Constraints:

  • 1 ⇐ grid.length ⇐ 100

  • 1 ⇐ grid[0].length ⇐ 100

  • grid[i][j] is 0 or 1

1
Unresolved directive in 1139-largest-1-bordered-square.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1139_Largest1BorderedSquare.java[]

1140. Stone Game II

Alex and Lee continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.

Alex and Lee take turns, with Alex starting first. Initially, M = 1.

On each player’s turn, that player can take all the stones in the first X remaining piles, where 1 ⇐ X ⇐ 2M. Then, we set M = max(M, X).

The game continues until all the stones have been taken.

Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.

Example 1:

Input: piles = [2,7,9,4,4]
Output: 10
Explanation:  If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning, then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since it's larger.

Constraints:

  • 1 ⇐ piles.length ⇐ 100

  • 1 ⇐ piles[i] ⇐ 10 ^ 4

1
Unresolved directive in 1140-stone-game-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1140_StoneGameII.java[]

1141. User Activity for the Past 30 Days I

1
Unresolved directive in 1141-user-activity-for-the-past-30-days-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1141_UserActivityForThePast30DaysI.java[]

1142. User Activity for the Past 30 Days II

1
Unresolved directive in 1142-user-activity-for-the-past-30-days-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1142_UserActivityForThePast30DaysII.java[]

1143. Longest Common Subsequence

Given two strings text1 and text2, return the length of their longest common subsequence.

A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 ⇐ text1.length ⇐ 1000

  • 1 ⇐ text2.length ⇐ 1000

  • The input strings consist of lowercase English characters only.

1
Unresolved directive in 1143-longest-common-subsequence.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1143_LongestCommonSubsequence.java[]

1144. Decrease Elements To Make Array Zigzag

Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.

An array A is a zigzag array if either:

  • Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > …​

  • OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < …​

Return the minimum number of moves to transform the given array nums into a zigzag array.

Example 1:

Input: nums = [1,2,3]
Output: 2
Explanation: We can decrease 2 to 0 or 3 to 1.

Example 2:

Input: nums = [9,6,1,6,2]
Output: 4

Constraints:

  • 1 ⇐ nums.length ⇐ 1000

  • 1 ⇐ nums[i] ⇐ 1000

1
Unresolved directive in 1144-decrease-elements-to-make-array-zigzag.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1144_DecreaseElementsToMakeArrayZigzag.java[]

1145. Binary Tree Coloring Game

Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.

Initially, the first player names a value x with 1 ⇐ x ⇐ n, and the second player names a value y with 1 ⇐ y ⇐ n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.

Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)

If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.

You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.

Example 1:

1480 binary tree coloring game
Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
Output: true
Explanation: The second player can choose the node with value 2.

Constraints:

  • root is the root of a binary tree with n nodes and distinct node values from 1 to n.

  • n is odd.

  • 1 ⇐ x ⇐ n ⇐ 100

1
Unresolved directive in 1145-binary-tree-coloring-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1145_BinaryTreeColoringGame.java[]

1146. Snapshot Array

Implement a SnapshotArray that supports the following interface:

  • SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.

  • void set(index, val) sets the element at the given index to be equal to val.

  • int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.

  • int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id

Example 1:

Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
Output: [null,null,0,null,5]
Explanation:
SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3
snapshotArr.set(0,5);  // Set array[0] = 5
snapshotArr.snap();  // Take a snapshot, return snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5

Constraints:

  • 1 ⇐ length ⇐ 50000

  • At most 50000 calls will be made to set, snap, and get.

  • 0 ⇐ index < length

  • 0 ⇐ snap_id < `(the total number of times we call `snap())

  • 0 ⇐ val ⇐ 10^9

1
Unresolved directive in 1146-snapshot-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1146_SnapshotArray.java[]

1147. Longest Chunked Palindrome Decomposition

Return the largest possible k such that there exists a_1, a_2, …​, a_k such that:

  • Each a_i is a non-empty string;

  • Their concatenation a_1 + a_2 + …​ + a_k is equal to text;

  • For all 1 ⇐ i ⇐ k, a_i = a_{k+1 - i}.

Example 1:

Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".

Example 2:

Input: text = "merchant"
Output: 1
Explanation: We can split the string on "(merchant)".

Example 3:

Input: text = "antaprezatepzapreanta"
Output: 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".

Example 4:

Input: text = "aaa"
Output: 3
Explanation: We can split the string on "(a)(a)(a)".

Constraints:

  • text consists only of lowercase English characters.

  • 1 ⇐ text.length ⇐ 1000

1
Unresolved directive in 1147-longest-chunked-palindrome-decomposition.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1147_LongestChunkedPalindromeDecomposition.java[]

1148. Article Views I

1
Unresolved directive in 1148-article-views-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1148_ArticleViewsI.java[]

1149. Article Views II

1
Unresolved directive in 1149-article-views-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1149_ArticleViewsII.java[]

1150. Check If a Number Is Majority Element in a Sorted Array

1
Unresolved directive in 1150-check-if-a-number-is-majority-element-in-a-sorted-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1150_CheckIfANumberIsMajorityElementInASortedArray.java[]

1151. Minimum Swaps to Group All 1’s Together

1
Unresolved directive in 1151-minimum-swaps-to-group-all-1s-together.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1151_MinimumSwapsToGroupAll1STogether.java[]

1152. Analyze User Website Visit Pattern

1
Unresolved directive in 1152-analyze-user-website-visit-pattern.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1152_AnalyzeUserWebsiteVisitPattern.java[]

1153. String Transforms Into Another String

1
Unresolved directive in 1153-string-transforms-into-another-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1153_StringTransformsIntoAnotherString.java[]

1154. Day of the Year

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"
Output: 41

Example 3:

Input: date = "2003-03-01"
Output: 60

Example 4:

Input: date = "2004-03-01"
Output: 61

Constraints:

  • date.length == 10

  • date[4] == date[7] == '-', and all other `date[i]’s are digits

  • date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

1
Unresolved directive in 1154-day-of-the-year.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1154_DayOfTheYear.java[]

1155. Number of Dice Rolls With Target Sum

You have d dice, and each die has f faces numbered 1, 2, …​, f.

Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.

Example 1:

Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces.  There is only one way to get a sum of 3.

Example 2:

Input: d = 2, f = 6, target = 7
Output: 6
Explanation:
You throw two dice, each with 6 faces.  There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:

Input: d = 2, f = 5, target = 10
Output: 1
Explanation:
You throw two dice, each with 5 faces.  There is only one way to get a sum of 10: 5+5.

Example 4:

Input: d = 1, f = 2, target = 3
Output: 0
Explanation:
You throw one die with 2 faces.  There is no way to get a sum of 3.

Example 5:

Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation:
The answer must be returned modulo 10^9 + 7.

Constraints:

  • 1 ⇐ d, f ⇐ 30

  • 1 ⇐ target ⇐ 1000

1
Unresolved directive in 1155-number-of-dice-rolls-with-target-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1155_NumberOfDiceRollsWithTargetSum.java[]

1156. Swap For Longest Repeated Character Substring

Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters.

Example 1:

Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa", which its length is 3.

Example 2:

Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa", which its length is 6.

Example 3:

Input: text = "aaabbaaa"
Output: 4

Example 4:

Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa", length is 5.

Example 5:

Input: text = "abcdef"
Output: 1

Constraints:

  • 1 ⇐ text.length ⇐ 20000

  • text consist of lowercase English characters only.

1
Unresolved directive in 1156-swap-for-longest-repeated-character-substring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1156_SwapForLongestRepeatedCharacterSubstring.java[]

1157. Online Majority Element In Subarray

Implementing the class MajorityChecker, which has the following API:

  • MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;

  • int query(int left, int right, int threshold) has arguments such that:

  • 0 ⇐ left ⇐ right < arr.length representing a subarray of arr;

  • 2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray

Each query(…​) returns the element in arr[left], arr[left+1], …​, arr[right] that occurs at least threshold times, or -1 if no such element exists.

Example:

MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2

Constraints:

  • 1 ⇐ arr.length ⇐ 20000

  • 1 ⇐ arr[i] ⇐ 20000

  • For each query, 0 ⇐ left ⇐ right < len(arr)

  • For each query, 2 * threshold > right - left + 1

  • The number of queries is at most 10000

1
Unresolved directive in 1157-online-majority-element-in-subarray.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1157_OnlineMajorityElementInSubarray.java[]

1158. Market Analysis I

1
Unresolved directive in 1158-market-analysis-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1158_MarketAnalysisI.java[]

1159. Market Analysis II

1
Unresolved directive in 1159-market-analysis-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1159_MarketAnalysisII.java[]

1160. Find Words That Can Be Formed by Characters

You are given an array of strings words and a string chars.

A string is good if it can be formed by characters from chars (each character can only be used once).

Return the sum of lengths of all good strings in words.

Example 1:

Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.

Example 2:

Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.

Note:

  1. 1 ⇐ words.length ⇐ 1000

  2. 1 ⇐ words[i].length, chars.length ⇐ 100

  3. All strings contain lowercase English letters only.

1
Unresolved directive in 1160-find-words-that-can-be-formed-by-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1160_FindWordsThatCanBeFormedByCharacters.java[]

1161. Maximum Level Sum of a Binary Tree

Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level X such that the sum of all the values of nodes at level X is maximal.

Example 1:

capture
Input: [1,7,0,7,-8,null,null]
Output: 2
Explanation:
Level 1 sum = 1.
Level 2 sum = 7 + 0 = 7.
Level 3 sum = 7 + -8 = -1.
So we return the level with the maximum sum which is level 2.

Note:

  1. The number of nodes in the given tree is between 1 and 10^4.

  2. -10^5 ⇐ node.val ⇐ 10^5

1
Unresolved directive in 1161-maximum-level-sum-of-a-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1161_MaximumLevelSumOfABinaryTree.java[]

1162. As Far from Land as Possible

Given an N x N grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized and return the distance.

The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.

If no land or water exists in the grid, return -1.

Example 1:

1336 ex1
Input: [[1,0,1],[0,0,0],[1,0,1]]
Output: 2
Explanation:
The cell (1, 1) is as far as possible from all the land with distance 2.

Example 2:

1336 ex2
Input: [[1,0,0],[0,0,0],[0,0,0]]
Output: 4
Explanation:
The cell (2, 2) is as far as possible from all the land with distance 4.

Note:

  1. 1 ⇐ grid.length == grid[0].length ⇐ 100

  2. grid[i][j] is 0 or 1

1
Unresolved directive in 1162-as-far-from-land-as-possible.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1162_AsFarFromLandAsPossible.java[]

1163. Last Substring in Lexicographical Order

Given a string s, return the last substring of s in lexicographical order.

Example 1:

Input: "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".

Example 2:

Input: "leetcode"
Output: "tcode"

Note:

  1. 1 ⇐ s.length ⇐ 4 * 10^5

  2. <font face="monospace">s contains only lowercase English letters.

1
Unresolved directive in 1163-last-substring-in-lexicographical-order.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1163_LastSubstringInLexicographicalOrder.java[]

1164. Product Price at a Given Date

1
Unresolved directive in 1164-product-price-at-a-given-date.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1164_ProductPriceAtAGivenDate.java[]

1165. Single-Row Keyboard

1
Unresolved directive in 1165-single-row-keyboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1165_SingleRowKeyboard.java[]

1166. Design File System

1
Unresolved directive in 1166-design-file-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1166_DesignFileSystem.java[]

1167. Minimum Cost to Connect Sticks

1
Unresolved directive in 1167-minimum-cost-to-connect-sticks.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1167_MinimumCostToConnectSticks.java[]

1168. Optimize Water Distribution in a Village

1
Unresolved directive in 1168-optimize-water-distribution-in-a-village.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1168_OptimizeWaterDistributionInAVillage.java[]

1169. Invalid Transactions

A transaction is possibly invalid if:

  • the amount exceeds $1000, or;

  • if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.

Each transaction string transactions[i] consists of comma separated values representing the name, time (in minutes), amount, and city of the transaction.

Given a list of transactions, return a list of transactions that are possibly invalid. You may return the answer in any order.

Example 1:

Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]
Output: ["alice,20,800,mtv","alice,50,100,beijing"]
Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.

Example 2:

Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]
Output: ["alice,50,1200,mtv"]

Example 3:

Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]
Output: ["bob,50,1200,mtv"]

Constraints:

  • transactions.length ⇐ 1000

  • Each transactions[i] takes the form "{name},{time},{amount},{city}"

  • Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.

  • Each {time} consist of digits, and represent an integer between 0 and 1000.

  • Each {amount} consist of digits, and represent an integer between 0 and 2000.

1
Unresolved directive in 1169-invalid-transactions.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1169_InvalidTransactions.java[]

1170. Compare Strings by Frequency of the Smallest Character

Let’s define a function f(s) over a non-empty string s, which calculates the frequency of the smallest character in s. For example, if s = "dcce" then f(s) = 2 because the smallest character is "c" and its frequency is 2.

Now, given string arrays queries and words, return an integer array answer, where each answer[i] is the number of words such that f(queries[i]) < f(W), where W is a word in words.

Example 1:

Input: queries = ["cbd"], words = ["zaaaz"]
Output: [1]
Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").

Example 2:

Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
Output: [1,2]
Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").

Constraints:

  • 1 ⇐ queries.length ⇐ 2000

  • 1 ⇐ words.length ⇐ 2000

  • 1 ⇐ queries[i].length, words[i].length ⇐ 10

  • queries[i][j], words[i][j] are English lowercase letters.

1
Unresolved directive in 1170-compare-strings-by-frequency-of-the-smallest-character.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1170_CompareStringsByFrequencyOfTheSmallestCharacter.java[]

1171. Remove Zero Sum Consecutive Nodes from Linked List

Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.

After doing so, return the head of the final linked list. You may return any such answer.

(Note that in the examples below, all sequences are serializations of ListNode objects.)

Example 1:

Input: head = [1,2,-3,3,1]
Output: [3,1]
Note: The answer [1,2,1] would also be accepted.

Example 2:

Input: head = [1,2,3,-3,4]
Output: [1,2,4]

Example 3:

Input: head = [1,2,3,-3,-2]
Output: [1]

Constraints:

  • The given linked list will contain between 1 and 1000 nodes.

  • Each node in the linked list has -1000 ⇐ node.val ⇐ 1000.

1
Unresolved directive in 1171-remove-zero-sum-consecutive-nodes-from-linked-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1171_RemoveZeroSumConsecutiveNodesFromLinkedList.java[]

1172. Dinner Plate Stacks

You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.

Implement the DinnerPlates class:

  • DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks.

  • void push(int val) pushes the given positive integer val into the leftmost stack with size less than capacity.

  • int pop() returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all stacks are empty.

  • int popAtStack(int index) returns the value at the top of the stack with the given index and removes it from that stack, and returns -1 if the stack with that given index is empty.

Example:

Input:
["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"]
[[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]
Output:
[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]

Explanation:
DinnerPlates D = DinnerPlates(2);  // Initialize with capacity = 2
D.push(1);
D.push(2);
D.push(3);
D.push(4);
D.push(5);         // The stacks are now:  2  4
                                           1  3  5
                                             
D.popAtStack(0);   // Returns 2.  The stacks are now:     4
                                                       1  3  5
                                                         
D.push(20);        // The stacks are now: 20  4
                                           1  3  5
                                             
D.push(21);        // The stacks are now: 20  4 21
                                           1  3  5
                                             
D.popAtStack(0);   // Returns 20.  The stacks are now:     4 21
                                                        1  3  5
                                                          
D.popAtStack(2);   // Returns 21.  The stacks are now:     4
                                                        1  3  5
                                                          
D.pop()            // Returns 5.  The stacks are now:      4
                                                        1  3
                                                         
D.pop()            // Returns 4.  The stacks are now:   1  3
                                                         
D.pop()            // Returns 3.  The stacks are now:   1
                                                        
D.pop()            // Returns 1.  There are no stacks.
D.pop()            // Returns -1.  There are still no stacks.

Constraints:

  • 1 ⇐ capacity ⇐ 20000

  • 1 ⇐ val ⇐ 20000

  • 0 ⇐ index ⇐ 100000

  • At most 200000 calls will be made to push, pop, and popAtStack.

1
Unresolved directive in 1172-dinner-plate-stacks.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1172_DinnerPlateStacks.java[]

1173. Immediate Food Delivery I

1
Unresolved directive in 1173-immediate-food-delivery-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1173_ImmediateFoodDeliveryI.java[]

1174. Immediate Food Delivery II

1
Unresolved directive in 1174-immediate-food-delivery-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1174_ImmediateFoodDeliveryII.java[]

1175. Prime Arrangements

Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)

(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)

Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:

Input: n = 5
Output: 12
Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.

Example 2:

Input: n = 100
Output: 682289015

Constraints:

  • 1 ⇐ n ⇐ 100

1
Unresolved directive in 1175-prime-arrangements.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1175_PrimeArrangements.java[]

1176. Diet Plan Performance

1
Unresolved directive in 1176-diet-plan-performance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1176_DietPlanPerformance.java[]

1177. Can Make Palindrome from Substring

Given a string s, we make queries on substrings of s.

For each query queries[i] = [left, right, k], we may rearrange the substring s[left], …​, s[right], and then choose up to k of them to replace with any lowercase English letter.

If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.

Return an array answer[], where answer[i] is the result of the i-th query queries[i].

Note that: Each letter is counted individually for replacement so if for example s[left..right] = "aaa", and k = 2, we can only replace two of the letters. (Also, note that the initial string s is never modified by any query.)

Example :

Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
Output: [true,false,false,true,true]
Explanation:
queries[0] : substring = "d", is palidrome.
queries[1] : substring = "bc", is not palidrome.
queries[2] : substring = "abcd", is not palidrome after replacing only 1 character.
queries[3] : substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries[4] : substring = "abcda", could be changed to "abcba" which is palidrome.

Constraints:

  • 1 ⇐ s.length, queries.length ⇐ 10^5

  • 0 ⇐ queries[i][0] ⇐ queries[i][1] < s.length

  • 0 ⇐ queries[i][2] ⇐ s.length

  • s only contains lowercase English letters.

1
Unresolved directive in 1177-can-make-palindrome-from-substring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1177_CanMakePalindromeFromSubstring.java[]

1178. Number of Valid Words for Each Puzzle

With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:

  • word contains the first letter of puzzle.

  • For each letter in word, that letter is in puzzle.

    For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage"; while invalid words are "beefed" (doesn't include "a") and "based" (includes "s" which isn't in the puzzle).

Return an array answer, where answer[i] is the number of words in the given word list words that are valid with respect to the puzzle puzzles[i].

Example :

Input:
words = ["aaaa","asas","able","ability","actt","actor","access"],
puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
Output: [1,1,3,2,4,0]
Explanation:
1 valid word for "aboveyz" : "aaaa"
1 valid word for "abrodyz" : "aaaa"
3 valid words for "abslute" : "aaaa", "asas", "able"
2 valid words for "absoryz" : "aaaa", "asas"
4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
There're no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.

Constraints:

  • 1 ⇐ words.length ⇐ 10^5

  • 4 ⇐ words[i].length ⇐ 50

  • 1 ⇐ puzzles.length ⇐ 10^4

  • puzzles[i].length == 7

  • words[i][j], puzzles[i][j] are English lowercase letters.

  • Each `puzzles[i] `doesn’t contain repeated characters.

1
Unresolved directive in 1178-number-of-valid-words-for-each-puzzle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1178_NumberOfValidWordsForEachPuzzle.java[]

1179. Reformat Department Table

Table: Department

------------------------+
| Column Name   | Type    |
------------------------+
| id            | int     |
| revenue       | int     |
| month         | varchar |
------------------------+
(id, month) is the primary key of this table.
The table has information about the revenue of each department per month.
The month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].

Write an SQL query to reformat the table such that there is a department id column and a revenue column for each month.

The query result format is in the following example:

Department table:
----------------------
| id   | revenue | month |
----------------------
| 1    | 8000    | Jan   |
| 2    | 9000    | Jan   |
| 3    | 10000   | Feb   |
| 1    | 7000    | Feb   |
| 1    | 6000    | Mar   |
----------------------

Result table:
---------------------------------------------------------------+
| id   | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |
---------------------------------------------------------------+
| 1    | 8000        | 7000        | 6000        | ... | null        |
| 2    | 9000        | null        | null        | ... | null        |
| 3    | null        | 10000       | null        | ... | null        |
---------------------------------------------------------------+

Note that the result table has 13 columns (1 for the department id + 12 for the months).
1
Unresolved directive in 1179-reformat-department-table.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1179_ReformatDepartmentTable.java[]

1180. Count Substrings with Only One Distinct Letter

1
Unresolved directive in 1180-count-substrings-with-only-one-distinct-letter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1180_CountSubstringsWithOnlyOneDistinctLetter.java[]

1181. Before and After Puzzle

1
Unresolved directive in 1181-before-and-after-puzzle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1181_BeforeAndAfterPuzzle.java[]

1182. Shortest Distance to Target Color

1
Unresolved directive in 1182-shortest-distance-to-target-color.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1182_ShortestDistanceToTargetColor.java[]

1183. Maximum Number of Ones

1
Unresolved directive in 1183-maximum-number-of-ones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1183_MaximumNumberOfOnes.java[]

1184. Distance Between Bus Stops

A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.

The bus goes along both directions i.e. clockwise and counterclockwise.

Return the shortest distance between the given start and destination stops.

Example 1:

untitled diagram 1
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.

Example 2:

untitled diagram 1 1
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.

Example 3:

untitled diagram 1 2
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.

Constraints:

  • 1 ⇐ n ⇐ 10^4

  • distance.length == n

  • 0 ⇐ start, destination < n

  • 0 ⇐ distance[i] ⇐ 10^4

1
Unresolved directive in 1184-distance-between-bus-stops.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1184_DistanceBetweenBusStops.java[]

1185. Day of the Week

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

Example 1:

Input: day = 31, month = 8, year = 2019
Output: "Saturday"

Example 2:

Input: day = 18, month = 7, year = 1999
Output: "Sunday"

Example 3:

Input: day = 15, month = 8, year = 1993
Output: "Sunday"

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

1
Unresolved directive in 1185-day-of-the-week.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1185_DayOfTheWeek.java[]

1186. Maximum Subarray Sum with One Deletion

Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.

Note that the subarray needs to be non-empty after deleting one element.

Example 1:

Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.

Example 2:

Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.

Example 3:

Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.

Constraints:

  • 1 ⇐ arr.length ⇐ 10^5

  • -10^4 ⇐ arr[i] ⇐ 10^4

1
Unresolved directive in 1186-maximum-subarray-sum-with-one-deletion.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1186_MaximumSubarraySumWithOneDeletion.java[]

1187. Make Array Strictly Increasing

Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.

In one operation, you can choose two indices 0 ⇐ i < arr1.length and 0 ⇐ j < arr2.length and do the assignment arr1[i] = arr2[j].

If there is no way to make arr1 strictly increasing, return -1.

Example 1:

Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
Output: 1
Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].

Example 2:

Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]
Output: 2
Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].

Example 3:

Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1 strictly increasing.

Constraints:

  • 1 ⇐ arr1.length, arr2.length ⇐ 2000

  • 0 ⇐ arr1[i], arr2[i] ⇐ 10^9

1
Unresolved directive in 1187-make-array-strictly-increasing.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1187_MakeArrayStrictlyIncreasing.java[]

1188. Design Bounded Blocking Queue

1
Unresolved directive in 1188-design-bounded-blocking-queue.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1188_DesignBoundedBlockingQueue.java[]

1189. Maximum Number of Balloons

Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.

You can use each character in text at most once. Return the maximum number of instances that can be formed.

Example 1:

1536 ex1 upd
Input: text = "nlaebolko"
Output: 1

Example 2:

1536 ex2 upd
Input: text = "loonbalxballpoon"
Output: 2

Example 3:

Input: text = "leetcode"
Output: 0

Constraints:

  • 1 ⇐ text.length ⇐ 10^4

  • text consists of lower case English letters only.

1
Unresolved directive in 1189-maximum-number-of-balloons.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1189_MaximumNumberOfBalloons.java[]

1190. Reverse Substrings Between Each Pair of Parentheses

You are given a string s that consists of lower case English letters and brackets.

Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should not contain any brackets.

Example 1:

Input: s = "(abcd)"
Output: "dcba"

Example 2:

Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.

Example 3:

Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.

Example 4:

Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"

Constraints:

  • 0 ⇐ s.length ⇐ 2000

  • s only contains lower case English characters and parentheses.

  • It’s guaranteed that all parentheses are balanced.

1
Unresolved directive in 1190-reverse-substrings-between-each-pair-of-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1190_ReverseSubstringsBetweenEachPairOfParentheses.java[]

1191. K-Concatenation Maximum Sum

Given an integer array arr and an integer k, modify the array by repeating it k times.

For example, if arr = [1, 2] and k = 3 `then the modified array will be `[1, 2, 1, 2, 1, 2].

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.

As the answer can be very large, return the answer modulo 10^9 + 7.

Example 1:

Input: arr = [1,2], k = 3
Output: 9

Example 2:

Input: arr = [1,-2,1], k = 5
Output: 2

Example 3:

Input: arr = [-1,-2], k = 7
Output: 0

Constraints:

  • 1 ⇐ arr.length ⇐ 10^5

  • 1 ⇐ k ⇐ 10^5

  • -10^4 ⇐ arr[i] ⇐ 10^4

1
Unresolved directive in 1191-k-concatenation-maximum-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1191_KConcatenationMaximumSum.java[]

1192. Critical Connections in a Network

There are n servers numbered from 0 to n-1 connected by undirected server-to-server connections forming a network where connections[i] = [a, b] represents a connection between servers a and b. Any server can reach any other server directly or indirectly through the network.

A critical connection is a connection that, if removed, will make some server unable to reach some other server.

Return all critical connections in the network in any order.

Example 1:

1537 ex1 2
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.

Constraints:

  • 1 ⇐ n ⇐ 10^5

  • n-1 ⇐ connections.length ⇐ 10^5

  • connections[i][0] != connections[i][1]

  • There are no repeated connections.

1
Unresolved directive in 1192-critical-connections-in-a-network.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1192_CriticalConnectionsInANetwork.java[]

1193. Monthly Transactions I

1
Unresolved directive in 1193-monthly-transactions-i.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1193_MonthlyTransactionsI.java[]

1194. Tournament Winners

1
Unresolved directive in 1194-tournament-winners.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1194_TournamentWinners.java[]

1195. Fizz Buzz Multithreaded

Write a program that outputs the string representation of numbers from 1 to n, however:

  • If the number is divisible by 3, output "fizz".

  • If the number is divisible by 5, output "buzz".

  • If the number is divisible by both 3 and 5, output "fizzbuzz".

For example, for n = 15, we output: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz.

Suppose you are given the following code:

class FizzBuzz {
  public FizzBuzz(int n) { ... }               // constructor
  public void fizz(printFizz) { ... }          // only output "fizz"
  public void buzz(printBuzz) { ... }          // only output "buzz"
  public void fizzbuzz(printFizzBuzz) { ... }  // only output "fizzbuzz"
  public void number(printNumber) { ... }      // only output the numbers
}

Implement a multithreaded version of FizzBuzz with four threads. The same instance of FizzBuzz will be passed to four different threads:

  • Thread A will call fizz() to check for divisibility of 3 and outputs fizz.

  • Thread B will call buzz() to check for divisibility of 5 and outputs buzz.

  • Thread C will call fizzbuzz() to check for divisibility of 3 and 5 and outputs fizzbuzz.

  • Thread D will call number() which should only output the numbers.

1
Unresolved directive in 1195-fizz-buzz-multithreaded.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1195_FizzBuzzMultithreaded.java[]

1196. How Many Apples Can You Put into the Basket

1
Unresolved directive in 1196-how-many-apples-can-you-put-into-the-basket.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1196_HowManyApplesCanYouPutIntoTheBasket.java[]

1197. Minimum Knight Moves

1
Unresolved directive in 1197-minimum-knight-moves.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1197_MinimumKnightMoves.java[]

1198. Find Smallest Common Element in All Rows

1
Unresolved directive in 1198-find-smallest-common-element-in-all-rows.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1198_FindSmallestCommonElementInAllRows.java[]

1199. Minimum Time to Build Blocks

1
Unresolved directive in 1199-minimum-time-to-build-blocks.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1199_MinimumTimeToBuildBlocks.java[]

1200. Minimum Absolute Difference

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

  • a, b are from arr

  • a < b

  • b - a equals to the minimum absolute difference of any two elements in arr

Example 1:

Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Example 2:

Input: arr = [1,3,6,10,15]
Output: [[1,3]]

Example 3:

Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]

Constraints:

  • 2 ⇐ arr.length ⇐ 10^5

  • -10^6 ⇐ arr[i] ⇐ 10^6

1
Unresolved directive in 1200-minimum-absolute-difference.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1200_MinimumAbsoluteDifference.java[]

1201. Ugly Number III

Write a program to find the n-th ugly number.

Ugly numbers are* positive integers* which are divisible by a or b or c.

Example 1:

Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.

Example 2:

Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.

Example 3:

Input: n = 5, a = 2, b = 11, c = 13
Output: 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.

Example 4:

Input: n = 1000000000, a = 2, b = 217983653, c = 336916467
Output: 1999999984

Constraints:

  • 1 ⇐ n, a, b, c ⇐ 10^9

  • 1 ⇐ a * b * c ⇐ 10^18

  • It’s guaranteed that the result will be in range [1, 2 * 10^9]

1
Unresolved directive in 1201-ugly-number-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1201_UglyNumberIII.java[]

1202. Smallest String With Swaps

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.

You can swap the characters at any pair of indices in the given pairs any number of times.

Return the lexicographically smallest string that s can be changed to after using the swaps.

Example 1:

Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"

Example 2:

Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination: 
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"

Example 3:

Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination: 
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"

Constraints:

  • 1 ⇐ s.length ⇐ 10^5

  • 0 ⇐ pairs.length ⇐ 10^5

  • 0 ⇐ pairs[i][0], pairs[i][1] < s.length

  • s only contains lower case English letters.

1
Unresolved directive in 1202-smallest-string-with-swaps.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1202_SmallestStringWithSwaps.java[]

1203. Sort Items by Groups Respecting Dependencies

There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it’s equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.

Return a sorted list of the items such that:

  • The items that belong to the same group are next to each other in the sorted list.

  • There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).

Return any solution if there is more than one solution and return an empty list if there is no solution.

Example 1:

1359 ex1
Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]
Output: [6,3,4,1,5,2,0,7]

Example 2:

Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]
Output: []
Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.

Constraints:

  • 1 ⇐ m ⇐ n ⇐ 3*10^4

  • group.length == beforeItems.length == n

  • -1 ⇐ group[i] ⇐ m-1

  • 0 ⇐ beforeItems[i].length ⇐ n-1

  • 0 ⇐ beforeItems[i][j] ⇐ n-1

  • i != beforeItems[i][j]

  • `beforeItems[i] `does not contain duplicates elements.

1
Unresolved directive in 1203-sort-items-by-groups-respecting-dependencies.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1203_SortItemsByGroupsRespectingDependencies.java[]

1204. Last Person to Fit in the Elevator

1
Unresolved directive in 1204-last-person-to-fit-in-the-elevator.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1204_LastPersonToFitInTheElevator.java[]

1205. Monthly Transactions II

1
Unresolved directive in 1205-monthly-transactions-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1205_MonthlyTransactionsII.java[]

1206. Design Skiplist

Design a Skiplist without using any built-in libraries.

A Skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists are just simple linked lists.

For example: we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:

1506 skiplist

Artyom Kalinin [CC BY-SA 3.0], via <a href="https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif" target="_blank" title="Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons">Wikimedia Commons</a>

You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add , erase and `search `can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).

To be specific, your design should include these functions:

  • bool search(int target) : Return whether the target exists in the Skiplist or not.

  • void add(int num): Insert a value into the SkipList.

  • bool erase(int num): Remove a value in the Skiplist. If num does not exist in the Skiplist, do nothing and return false. If there exists multiple num values, removing any one of them is fine.

See more about Skiplist : https://en.wikipedia.org/wiki/Skip_list

Note that duplicates may exist in the Skiplist, your code needs to handle this situation.

Example:

Skiplist skiplist = new Skiplist();

skiplist.add(1);
skiplist.add(2);
skiplist.add(3);
skiplist.search(0);   // return false.
skiplist.add(4);
skiplist.search(1);   // return true.
skiplist.erase(0);    // return false, 0 is not in skiplist.
skiplist.erase(1);    // return true.
skiplist.search(1);   // return false, 1 has already been erased.

Constraints:

  • 0 ⇐ num, target ⇐ 20000

  • At most 50000 calls will be made to search, add, and erase.

1
Unresolved directive in 1206-design-skiplist.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1206_DesignSkiplist.java[]

1207. Unique Number of Occurrences

Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.

Example 1:

Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true

Constraints:

  • 1 ⇐ arr.length ⇐ 1000

  • -1000 ⇐ arr[i] ⇐ 1000

1
Unresolved directive in 1207-unique-number-of-occurrences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1207_UniqueNumberOfOccurrences.java[]

1208. Get Equal Substrings Within Budget

You are given two strings s and t of the same length. You want to change s to t. Changing the i-th character of s to i-th character of t costs |s[i] - t[i]| that is, the absolute difference between the ASCII values of the characters.

You are also given an integer maxCost.

Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t`with a cost less than or equal to `maxCost.

If there is no substring from s that can be changed to its corresponding substring from t, return 0.

Example 1:

Input: s = "abcd", t = "bcdf", maxCost = 3
Output: 3
Explanation:"abc" of s can change to "bcd". That costs 3, so the maximum length is 3.

Example 2:

Input: s = "abcd", t = "cdef", maxCost = 3
Output: 1
Explanation: Each character in s costs 2 to change to charactor in t, so the maximum length is 1.

Example 3:

Input: s = "abcd", t = "acde", maxCost = 0
Output: 1
Explanation: You can't make any change, so the maximum length is 1.

Constraints:

  • 1 ⇐ s.length, t.length ⇐ 10^5

  • 0 ⇐ maxCost ⇐ 10^6

  • s and t only contain lower case English letters.

1
Unresolved directive in 1208-get-equal-substrings-within-budget.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1208_GetEqualSubstringsWithinBudget.java[]

1209. Remove All Adjacent Duplicates in String II

Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made.

It is guaranteed that the answer is unique.

Example 1:

Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"

Constraints:

  • 1 ⇐ s.length ⇐ 10^5

  • 2 ⇐ k ⇐ 10^4

  • s only contains lower case English letters.

1
Unresolved directive in 1209-remove-all-adjacent-duplicates-in-string-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1209_RemoveAllAdjacentDuplicatesInStringII.java[]

1210. Minimum Moves to Reach Target with Rotations

In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).

In one move the snake can:

  • Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.

  • Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.

  • Rotate clockwise if it’s in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).

image 2
  • Rotate counterclockwise if it’s in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).

image 1

Return the minimum number of moves to reach the target.

If there is no way to reach the target, return -1.

Example 1:

image
Input: grid = [[0,0,0,0,0,1],
               [1,1,0,0,1,0],
               [0,0,0,0,1,1],
               [0,0,1,0,1,0],
               [0,1,1,0,0,0],
               [0,1,1,0,0,0]]
Output: 11
Explanation:
One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].

Example 2:

Input: grid = [[0,0,1,1,1,1],
               [0,0,0,0,1,1],
               [1,1,0,0,0,1],
               [1,1,1,0,0,1],
               [1,1,1,0,0,1],
               [1,1,1,0,0,0]]
Output: 9

Constraints:

  • 2 ⇐ n ⇐ 100

  • 0 ⇐ grid[i][j] ⇐ 1

  • It is guaranteed that the snake starts at empty cells.

1
Unresolved directive in 1210-minimum-moves-to-reach-target-with-rotations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1210_MinimumMovesToReachTargetWithRotations.java[]

1211. Queries Quality and Percentage

1
Unresolved directive in 1211-queries-quality-and-percentage.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1211_QueriesQualityAndPercentage.java[]

1212. Team Scores in Football Tournament

1
Unresolved directive in 1212-team-scores-in-football-tournament.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1212_TeamScoresInFootballTournament.java[]

1213. Intersection of Three Sorted Arrays

1
Unresolved directive in 1213-intersection-of-three-sorted-arrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1213_IntersectionOfThreeSortedArrays.java[]

1214. Two Sum BSTs

1
Unresolved directive in 1214-two-sum-bsts.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1214_TwoSumBSTs.java[]

1215. Stepping Numbers

1
Unresolved directive in 1215-stepping-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1215_SteppingNumbers.java[]

1216. Valid Palindrome III

1
Unresolved directive in 1216-valid-palindrome-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1216_ValidPalindromeIII.java[]

1217. Play with Chips

There are some chips, and the i-th chip is at position chips[i].

You can perform any of the two following types of moves any number of times (possibly zero) on any chip:

  • Move the i-th chip by 2 units to the left or to the right with a cost of 0.

  • Move the i-th chip by 1 unit to the left or to the right with a cost of 1.

There can be two or more chips at the same position initially.

Return the minimum cost needed to move all the chips to the same position (any position).

Example 1:

Input: chips = [1,2,3]
Output: 1
Explanation: Second chip will be moved to positon 3 with cost 1. First chip will be moved to position 3 with cost 0. Total cost is 1.

Example 2:

Input: chips = [2,2,2,3,3]
Output: 2
Explanation: Both fourth and fifth chip will be moved to position two with cost 1. Total minimum cost will be 2.

Constraints:

  • 1 ⇐ chips.length ⇐ 100

  • 1 ⇐ chips[i] ⇐ 10^9

1
Unresolved directive in 1217-play-with-chips.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1217_PlayWithChips.java[]

1218. Longest Arithmetic Subsequence of Given Difference

Given an integer array arr and an integer <font face="monospace">difference, return the length of the longest subsequence in <font face="monospace">`arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

Example 1:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

Example 2:

Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

Example 3:

Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].

Constraints:

  • 1 ⇐ arr.length ⇐ 10^5

  • -10^4 ⇐ arr[i], difference ⇐ 10^4

1
Unresolved directive in 1218-longest-arithmetic-subsequence-of-given-difference.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1218_LongestArithmeticSubsequenceOfGivenDifference.java[]

1219. Path with Maximum Gold

In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.

Return the maximum amount of gold you can collect under the conditions:

  • Every time you are located in a cell you will collect all the gold in that cell.

  • From your position you can walk one step to the left, right, up or down.

  • You can’t visit the same cell more than once.

  • Never visit a cell with 0 gold.

  • You can start and stop collecting gold from *any *position in the grid that has some gold.

Example 1:

Input: grid = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24
Explanation:
[[0,6,0],
 [5,8,7],
 [0,9,0]]
Path to get the maximum gold, 9 -> 8 -> 7.

Example 2:

Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
Output: 28
Explanation:
[[1,0,7],
 [2,0,6],
 [3,4,5],
 [0,3,0],
 [9,0,20]]
Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.

Constraints:

  • 1 ⇐ grid.length, grid[i].length ⇐ 15

  • 0 ⇐ grid[i][j] ⇐ 100

  • There are at most *25 *cells containing gold.

1
Unresolved directive in 1219-path-with-maximum-gold.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1219_PathWithMaximumGold.java[]

1220. Count Vowels Permutation

Given an integer n, your task is to count how many strings of length n can be formed under the following rules:

  • Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')

  • Each vowel 'a' may only be followed by an 'e'.

  • Each vowel 'e' may only be followed by an 'a' or an 'i'.

  • Each vowel 'i' may not be followed by another 'i'.

  • Each vowel 'o' may only be followed by an 'i' or a 'u'.

  • Each vowel 'u' may only be followed by an 'a'.

Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".

Example 2:

Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".

*Example 3: *

Input: n = 5
Output: 68

Constraints:

  • 1 ⇐ n ⇐ 2 * 10^4

1
Unresolved directive in 1220-count-vowels-permutation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1220_CountVowelsPermutation.java[]

1221. Split a String in Balanced Strings

<i data-stringify-type="italic">Balanced_ strings are those who have equal quantity of 'L' and 'R' characters.

Given a balanced string <code data-stringify-type="code">s` split it in the maximum amount of balanced strings.

Return the maximum amount of splitted balanced strings.

Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Constraints:

  • 1 ⇐ s.length ⇐ 1000

  • s[i] = 'L' or 'R'

1
Unresolved directive in 1221-split-a-string-in-balanced-strings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1221_SplitAStringInBalancedStrings.java[]

1222. Queens That Can Attack the King

On an 8x8 chessboard, there can be multiple Black Queens and one White King.

Given an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.

Example 1:

untitled diagram
Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
Output: [[0,1],[1,0],[3,3]]
Explanation:
The queen at [0,1] can attack the king cause they're in the same row.
The queen at [1,0] can attack the king cause they're in the same column.
The queen at [3,3] can attack the king cause they're in the same diagnal.
The queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1].
The queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0].
The queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.

Example 2:

untitled diagram 1
Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
Output: [[2,2],[3,4],[4,4]]

Example 3:

untitled diagram 2
Input: queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]
Output: [[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]

Constraints:

  • 1 ⇐ queens.length ⇐ 63

  • queens[0].length == 2

  • 0 ⇐ queens[i][j] < 8

  • king.length == 2

  • 0 ⇐ king[0], king[1] < 8

  • At most one piece is allowed in a cell.

1
Unresolved directive in 1222-queens-that-can-attack-the-king.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1222_QueensThatCanAttackTheKing.java[]

1223. Dice Roll Simulation

A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.

Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls.

Two sequences are considered different if at least one element differs from each other. Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: n = 2, rollMax = [1,1,2,2,2,3]
Output: 34
Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.

Example 2:

Input: n = 2, rollMax = [1,1,1,1,1,1]
Output: 30

Example 3:

Input: n = 3, rollMax = [1,1,1,2,2,3]
Output: 181

Constraints:

  • 1 ⇐ n ⇐ 5000

  • rollMax.length == 6

  • 1 ⇐ rollMax[i] ⇐ 15

1
Unresolved directive in 1223-dice-roll-simulation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1223_DiceRollSimulation.java[]

1224. Maximum Equal Frequency

Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.

If after removing one element there are no remaining elements, it’s still considered that every appeared number has the same number of ocurrences (0).

Example 1:

Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.

Example 2:

Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13

Example 3:

Input: nums = [1,1,1,2,2,2]
Output: 5

Example 4:

Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]
Output: 8

Constraints:

  • 2 ⇐ nums.length ⇐ 10^5

  • 1 ⇐ nums[i] ⇐ 10^5

1
Unresolved directive in 1224-maximum-equal-frequency.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1224_MaximumEqualFrequency.java[]

1225. Report Contiguous Dates

1
Unresolved directive in 1225-report-contiguous-dates.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1225_ReportContiguousDates.java[]

1226. The Dining Philosophers

Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.

Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.

Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.

Design a discipline of behavior (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.

an illustration of the dining philosophers problem

The problem statement and the image above are taken from wikipedia.org

The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:

  • philosopher is the id of the philosopher who wants to eat.

  • pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.

  • eat is a function you can call to let the philosopher eat once he has picked both forks.

  • putLeftFork and pickRightFork are functions you can call to put down the corresponding forks of that philosopher.

  • The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number).

Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. It is possible that the function will be called for the same philosopher more than once, even before the last call ends.

Example 1:

Input: n = 1
Output: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]
Explanation:
n is the number of times each philosopher will call the function.
The output array describes the calls you made to the functions controlling the forks and the eat function, its format is:
output[i] = [a, b, c] (three integers)
- a is the id of a philosopher.
- b specifies the fork: {1 : left, 2 : right}.
- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.

Constraints:

  • 1 ⇐ n ⇐ 60

1
Unresolved directive in 1226-the-dining-philosophers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1226_TheDiningPhilosophers.java[]

1227. Airplane Seat Assignment Probability

<code data-stringify-type="code">n` passengers board an airplane with exactly <code data-stringify-type="code">n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of passengers will:

  • Take their own seat if it is still available,

  • Pick other seats randomly when they find their seat occupied

What is the probability that the n-th person can get his own seat?

Example 1:

Input: n = 1
Output: 1.00000
Explanation: The first person can only get the first seat.

Example 2:

Input: n = 2
Output: 0.50000
Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).

Constraints:

  • 1 ⇐ n ⇐ 10^5

1
Unresolved directive in 1227-airplane-seat-assignment-probability.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1227_AirplaneSeatAssignmentProbability.java[]

1228. Missing Number In Arithmetic Progression

1
Unresolved directive in 1228-missing-number-in-arithmetic-progression.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1228_MissingNumberInArithmeticProgression.java[]

1229. Meeting Scheduler

1
Unresolved directive in 1229-meeting-scheduler.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1229_MeetingScheduler.java[]

1230. Toss Strange Coins

1
Unresolved directive in 1230-toss-strange-coins.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1230_TossStrangeCoins.java[]

1231. Divide Chocolate

1
Unresolved directive in 1231-divide-chocolate.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1231_DivideChocolate.java[]

1232. Check If It Is a Straight Line

You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.

Example 1:

untitled diagram 2
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true

Example 2:

untitled diagram 1
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false

Constraints:

  • 2 ⇐ coordinates.length ⇐ 1000

  • coordinates[i].length == 2

  • -10^4 ⇐ coordinates[i][0], coordinates[i][1] ⇐ 10^4

  • coordinates contains no duplicate point.

1
Unresolved directive in 1232-check-if-it-is-a-straight-line.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1232_CheckIfItIsAStraightLine.java[]

1233. Remove Sub-Folders from the Filesystem

Given a list of folders, remove all sub-folders in those folders and return in any order the folders after removing.

If a folder[i] is located within another folder[j], it is called a sub-folder of it.

The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, /leetcode and /leetcode/problems are valid paths while an empty string and / are not.

Example 1:

Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b/" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.

Example 2:

Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d/" will be removed because they are subfolders of "/a".

Example 3:

Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]

Constraints:

  • 1 ⇐ folder.length ⇐ 4 * 10^4

  • 2 ⇐ folder[i].length ⇐ 100

  • folder[i] contains only lowercase letters and '/'

  • folder[i] always starts with character '/'

  • Each folder name is unique.

1
Unresolved directive in 1233-remove-sub-folders-from-the-filesystem.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1233_RemoveSubFoldersFromTheFilesystem.java[]

1234. Replace the Substring for Balanced String

You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.

A string is said to be *balanced*_ _if each of its characters appears n/4 times where n is the length of the string.

Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.

Return 0 if the string is already balanced.

Example 1:

Input: s = "QWER"
Output: 0
Explanation: s is already balanced.

Example 2:

Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.

Example 3:

Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".

Example 4:

Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".

Constraints:

  • 1 ⇐ s.length ⇐ 10^5

  • s.length is a multiple of 4

  • s `contains only ’Q', 'W', 'E' and 'R'.

1
Unresolved directive in 1234-replace-the-substring-for-balanced-string.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1234_ReplaceTheSubstringForBalancedString.java[]

1235. Maximum Profit in Job Scheduling

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

You’re given the startTime , endTime and profit arrays, you need to output the maximum profit you can take such that there are no 2 jobs in the subset with overlapping time range.

If you choose a job that ends at time X you will be able to start another job that starts at time X.

Example 1:

sample1 1584
Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job.
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.

Example 2:

sample22 1584

Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.

Example 3:

sample3 1584
Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6

Constraints:

  • 1 ⇐ startTime.length == endTime.length == profit.length ⇐ 5 * 10^4

  • 1 ⇐ startTime[i] < endTime[i] ⇐ 10^9

  • 1 ⇐ profit[i] ⇐ 10^4

1
Unresolved directive in 1235-maximum-profit-in-job-scheduling.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1235_MaximumProfitInJobScheduling.java[]

1236. Web Crawler

1
Unresolved directive in 1236-web-crawler.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1236_WebCrawler.java[]

1237. Find Positive Integer Solution for a Given Equation

Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.

The function is constantly increasing, i.e.:

  • f(x, y) < f(x + 1, y)

  • f(x, y) < f(x, y + 1)

The function interface is defined like this:

interface CustomFunction {
public:
  // Returns positive integer f(x, y) for any given positive integer x and y.
  int f(int x, int y);
};

For custom testing purposes you’re given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you’ll know only two functions from the list.

You may return the solutions in any order.

Example 1:

Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]
Explanation: function_id = 1 means that f(x, y) = x + y

Example 2:

Input: function_id = 2, z = 5
Output: [[1,5],[5,1]]
Explanation: function_id = 2 means that f(x, y) = x * y

Constraints:

  • 1 ⇐ function_id ⇐ 9

  • 1 ⇐ z ⇐ 100

  • It’s guaranteed that the solutions of f(x, y) == z will be on the range 1 ⇐ x, y ⇐ 1000

  • It’s also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 ⇐ x, y ⇐ 1000

1
Unresolved directive in 1237-find-positive-integer-solution-for-a-given-equation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1237_FindPositiveIntegerSolutionForAGivenEquation.java[]

1238. Circular Permutation in Binary Representation

Given 2 integers n and start. Your task is return any permutation p of `(0,1,2…​..,2^n -1) `such that :

  • p[0] = start

  • p[i] and p[i+1] differ by only one bit in their binary representation.

  • p[0] and p[2^n -1] must also differ by only one bit in their binary representation.

Example 1:

Input: n = 2, start = 3
Output: [3,2,0,1]
Explanation: The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]

Example 2:

Input: n = 3, start = 2
Output: [2,6,7,5,4,0,1,3]
Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).

Constraints:

  • 1 ⇐ n ⇐ 16

  • 0 ⇐ start < 2 ^ n

1
Unresolved directive in 1238-circular-permutation-in-binary-representation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1238_CircularPermutationInBinaryRepresentation.java[]

1239. Maximum Length of a Concatenated String with Unique Characters

Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.

Return the maximum possible length of s.

Example 1:

Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.

Example 2:

Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".

Example 3:

Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26

Constraints:

  • 1 ⇐ arr.length ⇐ 16

  • 1 ⇐ arr[i].length ⇐ 26

  • arr[i] contains only lower case English letters.

1
Unresolved directive in 1239-maximum-length-of-a-concatenated-string-with-unique-characters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1239_MaximumLengthOfAConcatenatedStringWithUniqueCharacters.java[]

1240. Tiling a Rectangle with the Fewest Squares

Given a rectangle of size n x <font face="monospace">m, find the minimum number of integer-sided squares that tile the rectangle.

Example 1:

sample 11 1592
Input: n = 2, m = 3
Output: 3
Explanation: 3 squares are necessary to cover the rectangle.
2 (squares of 1x1)
1 (square of 2x2)

Example 2:

sample 22 1592
Input: n = 5, m = 8
Output: 5

Example 3:

sample 33 1592
Input: n = 11, m = 13
Output: 6

Constraints:

  • 1 ⇐ n ⇐ 13

  • 1 ⇐ m ⇐ 13

1
Unresolved directive in 1240-tiling-a-rectangle-with-the-fewest-squares.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1240_TilingARectangleWithTheFewestSquares.java[]

1241. Number of Comments per Post

1
Unresolved directive in 1241-number-of-comments-per-post.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1241_NumberOfCommentsPerPost.java[]

1242. Web Crawler Multithreaded

1
Unresolved directive in 1242-web-crawler-multithreaded.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1242_WebCrawlerMultithreaded.java[]

1243. Array Transformation

1
Unresolved directive in 1243-array-transformation.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1243_ArrayTransformation.java[]

1244. Design A Leaderboard

1
Unresolved directive in 1244-design-a-leaderboard.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1244_DesignALeaderboard.java[]

1245. Tree Diameter

1
Unresolved directive in 1245-tree-diameter.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1245_TreeDiameter.java[]

1246. Palindrome Removal

1
Unresolved directive in 1246-palindrome-removal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1246_PalindromeRemoval.java[]

1247. Minimum Swaps to Make Strings Equal

You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].

Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:

Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

*Example 2: *

Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.

Example 3:

Input: s1 = "xx", s2 = "xy"
Output: -1

Example 4:

Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4

Constraints:

  • 1 ⇐ s1.length, s2.length ⇐ 1000

  • s1, s2 only contain 'x' or 'y'.

1
Unresolved directive in 1247-minimum-swaps-to-make-strings-equal.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1247_MinimumSwapsToMakeStringsEqual.java[]

1248. Count Number of Nice Subarrays

Given an array of integers nums and an integer k. A_ _subarray is called nice if there are k odd numbers on it.

Return the number of nice sub-arrays.

Example 1:

Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1
Output: 0
Explanation: There is no odd numbers in the array.

Example 3:

Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16

Constraints:

  • 1 ⇐ nums.length ⇐ 50000

  • 1 ⇐ nums[i] ⇐ 10^5

  • 1 ⇐ k ⇐ nums.length

1
Unresolved directive in 1248-count-number-of-nice-subarrays.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1248_CountNumberOfNiceSubarrays.java[]

1249. Minimum Remove to Make Valid Parentheses

Given a string <font face="monospace">s of '(' , ')' and lowercase English characters.

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, contains only lowercase characters, or

  • It can be written as AB (A concatenated with B), where A and B are valid strings, or

  • It can be written as (A), where A is a valid string.

Example 1:

Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Example 4:

Input: s = "(a(b(c)d)"
Output: "a(b(c)d)"

Constraints:

  • 1 ⇐ s.length ⇐ 10^5

  • s[i] is one of '(' , ')' and lowercase English letters`.`

1
Unresolved directive in 1249-minimum-remove-to-make-valid-parentheses.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1249_MinimumRemoveToMakeValidParentheses.java[]

1250. Check If It Is a Good Array

Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be *good *if you can obtain a sum of 1 from the array by any possible subset and multiplicand.

Return True if the array is *good *otherwise return False.

Example 1:

Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
53 + 7(-2) = 1

Example 2:

Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
291 + 6(-3) + 10*(-1) = 1

Example 3:

Input: nums = [3,6]
Output: false

Constraints:

  • 1 ⇐ nums.length ⇐ 10^5

  • 1 ⇐ nums[i] ⇐ 10^9

1
Unresolved directive in 1250-check-if-it-is-a-good-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1250_CheckIfItIsAGoodArray.java[]

1251. Average Selling Price

1
Unresolved directive in 1251-average-selling-price.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1251_AverageSellingPrice.java[]

1252. Cells with Odd Values in a Matrix

Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.

Return the number of cells with odd values in the matrix after applying the increment to all indices.

Example 1:

e1
Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.

Example 2:

e2
Input: n = 2, m = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.

Constraints:

  • 1 ⇐ n ⇐ 50

  • 1 ⇐ m ⇐ 50

  • 1 ⇐ indices.length ⇐ 100

  • 0 ⇐ indices[i][0] < n

  • 0 ⇐ indices[i][1] < m

1
Unresolved directive in 1252-cells-with-odd-values-in-a-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1252_CellsWithOddValuesInAMatrix.java[]

1253. Reconstruct a 2-Row Binary Matrix

Given the following details of a matrix with n columns and 2 rows :

  • The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.

  • The sum of elements of the 0-th(upper) row is given as upper.

  • The sum of elements of the 1-st(lower) row is given as lower.

  • The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.

Your task is to reconstruct the matrix with upper, lower and colsum.

Return it as a 2-D integer array.

If there are more than one valid solution, any of them will be accepted.

If no valid solution exists, return an empty 2-D array.

Example 1:

Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.

Example 2:

Input: upper = 2, lower = 3, colsum = [2,2,1,1]
Output: []

Example 3:

Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]

Constraints:

  • 1 ⇐ colsum.length ⇐ 10^5

  • 0 ⇐ upper, lower ⇐ colsum.length

  • 0 ⇐ colsum[i] ⇐ 2

1
Unresolved directive in 1253-reconstruct-a-2-row-binary-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1253_ReconstructA2RowBinaryMatrix.java[]

1254. Number of Closed Islands

Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of <font face="monospace">0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.

Return the number of closed islands.

Example 1:

sample 3 1610
Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Output: 2
Explanation:
Islands in gray are closed because they are completely surrounded by water (group of 1s).

Example 2:

sample 4 1610
Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
Output: 1

Example 3:

Input: grid = [[1,1,1,1,1,1,1],
               [1,0,0,0,0,0,1],
               [1,0,1,1,1,0,1],
               [1,0,1,0,1,0,1],
               [1,0,1,1,1,0,1],
               [1,0,0,0,0,0,1],
               [1,1,1,1,1,1,1]]
Output: 2

Constraints:

  • 1 ⇐ grid.length, grid[0].length ⇐ 100

  • 0 ⇐ grid[i][j] ⇐1

1
Unresolved directive in 1254-number-of-closed-islands.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1254_NumberOfClosedIslands.java[]

1255. Maximum Score Words Formed by Letters

Given a list of words, list of single letters (might be repeating) and score of every character.

Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).

It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', …​ ,'z' is given by score[0], score[1], …​ , score[25] respectively.

Example 1:

Input: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]
Output: 23
Explanation:
Score  a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.
Words "dad" and "dog" only get a score of 21.

Example 2:

Input: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]
Output: 27
Explanation:
Score  a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.
Word "xxxz" only get a score of 25.

Example 3:

Input: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]
Output: 0
Explanation:
Letter "e" can only be used once.

Constraints:

  • 1 ⇐ words.length ⇐ 14

  • 1 ⇐ words[i].length ⇐ 15

  • 1 ⇐ letters.length ⇐ 100

  • letters[i].length == 1

  • score.length == 26

  • 0 ⇐ score[i] ⇐ 10

  • words[i], letters[i] contains only lower case English letters.

1
Unresolved directive in 1255-maximum-score-words-formed-by-letters.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1255_MaximumScoreWordsFormedByLetters.java[]

1256. Encode Number

1
Unresolved directive in 1256-encode-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1256_EncodeNumber.java[]

1257. Smallest Common Region

1
Unresolved directive in 1257-smallest-common-region.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1257_SmallestCommonRegion.java[]

1258. Synonymous Sentences

1
Unresolved directive in 1258-synonymous-sentences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1258_SynonymousSentences.java[]

1259. Handshakes That Don’t Cross

1
Unresolved directive in 1259-handshakes-that-dont-cross.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1259_HandshakesThatDonTCross.java[]

1260. Shift 2D Grid

Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.

In one shift operation:

  • Element at grid[i][j] moves to grid[i][j + 1].

  • Element at grid[i][n - 1] moves to grid[i + 1][0].

  • Element at grid[m - 1][n - 1] moves to grid[0][0].

Return the 2D grid after applying shift operation k times.

Example 1:

e1
Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]

Example 2:

e2
Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 1 ⇐ m ⇐ 50

  • 1 ⇐ n ⇐ 50

  • -1000 ⇐ grid[i][j] ⇐ 1000

  • 0 ⇐ k ⇐ 100

1
Unresolved directive in 1260-shift-2d-grid.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1260_Shift2DGrid.java[]

1261. Find Elements in a Contaminated Binary Tree

Given a binary tree with the following rules:

  • root.val == 0

  • If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1

  • If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2

Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.

You need to first recover the binary tree and then implement the FindElements class:

  • FindElements(TreeNode* root) Initializes the object with a contamined binary tree, you need to recover it first.

  • bool find(int target) Return if the target value exists in the recovered binary tree.

Example 1:

untitled diagram 4 1
Input
["FindElements","find","find"]
[[[-1,null,-1]],[1],[2]]
Output
[null,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1]);
findElements.find(1); // return False
findElements.find(2); // return True

Example 2:

untitled diagram 4
Input
["FindElements","find","find","find"]
[[[-1,-1,-1,-1,-1]],[1],[3],[5]]
Output
[null,true,true,false]
Explanation
FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False

Example 3:

untitled diagram 4 1 1
Input
["FindElements","find","find","find","find"]
[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]
Output
[null,true,false,false,true]
Explanation
FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True

Constraints:

  • TreeNode.val == -1

  • The height of the binary tree is less than or equal to 20

  • The total number of nodes is between [1, 10^4]

  • Total calls of find() is between [1, 10^4]

  • 0 ⇐ target ⇐ 10^6

1
Unresolved directive in 1261-find-elements-in-a-contaminated-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1261_FindElementsInAContaminatedBinaryTree.java[]

1262. Greatest Sum Divisible by Three

Given an array nums of integers, we need to find the maximum possible sum of elements of the array such that it is divisible by three.

Example 1:

Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).

Example 2:

Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.

Example 3:

Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).

Constraints:

  • 1 ⇐ nums.length ⇐ 4 * 10^4

  • 1 ⇐ nums[i] ⇐ 10^4

1
Unresolved directive in 1262-greatest-sum-divisible-by-three.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1262_GreatestSumDivisibleByThree.java[]

1263. Minimum Moves to Move a Box to Their Target Location

Storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.

The game is represented by a grid of size m x n, where each element is a wall, floor, or a box.

Your task is move the box 'B' to the target position 'T' under the following rules:

  • Player is represented by character 'S' and can move up, down, left, right in the grid if it is a floor (empy cell).

  • Floor is represented by character '.' that means free cell to walk.

  • Wall is represented by character '#' that means obstacle (impossible to walk there).

  • There is only one box 'B' and one target cell 'T' in the grid.

  • The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.

  • The player cannot walk through the box.

Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.

Example 1:

sample 1 1620
Input: grid = [["","","","","",""],
               ["","T","","","",""],
               ["",".",".","B",".",""],
               ["",".","","",".",""],
               ["",".",".",".","S",""],
               ["","","","","","#"]]
Output: 3
Explanation: We return only the number of times the box is pushed.

Example 2:

Input: grid = [["","","","","",""],
               ["","T","","","",""],
               ["",".",".","B",".",""],
               ["","","","",".",""],
               ["",".",".",".","S",""],
               ["","","","","",""]]
Output: -1

Example 3:

Input: grid = [["","","","","",""],
               ["","T",".",".","",""],
               ["",".","","B",".",""],
               ["",".",".",".",".",""],
               ["",".",".",".","S",""],
               ["","","","","",""]]
Output: 5
Explanation:  push the box down, left, left, up and up.

Example 4:

Input: grid = [["","","","","","",""],
               ["","S","",".","B","T",""],
               ["","","","","","","#"]]
Output: -1

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 1 ⇐ m ⇐ 20

  • 1 ⇐ n ⇐ 20

  • grid contains only characters '.', '#', 'S' , 'T', or 'B'.

  • There is only one character 'S', 'B' <font face="sans-serif, Arial, Verdana, Trebuchet MS">and 'T' in the grid.

1
Unresolved directive in 1263-minimum-moves-to-move-a-box-to-their-target-location.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1263_MinimumMovesToMoveABoxToTheirTargetLocation.java[]

1264. Page Recommendations

1
Unresolved directive in 1264-page-recommendations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1264_PageRecommendations.java[]

1265. Print Immutable Linked List in Reverse

1
Unresolved directive in 1265-print-immutable-linked-list-in-reverse.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1265_PrintImmutableLinkedListInReverse.java[]

1266. Minimum Time Visiting All Points

On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points.

You can move according to the next rules:

  • In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second).

  • You have to visit the points in the same order as they appear in the array.

Example 1:

1626 example 1
Input: points = [[1,1],[3,4],[-1,0]]
Output: 7
Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0]
Time from [1,1] to [3,4] = 3 seconds
Time from [3,4] to [-1,0] = 4 seconds
Total time = 7 seconds

Example 2:

Input: points = [[3,2],[-2,2]]
Output: 5

Constraints:

  • points.length == n

  • 1 ⇐ n ⇐ 100

  • points[i].length == 2

  • -1000 ⇐ points[i][0], points[i][1] ⇐ 1000

1
Unresolved directive in 1266-minimum-time-visiting-all-points.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1266_MinimumTimeVisitingAllPoints.java[]

1267. Count Servers that Communicate

You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.

Return the number of servers that communicate with any other server.

Example 1:

untitled diagram 6
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.

Example 2:

untitled diagram 4
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.

Example 3:

untitled diagram 1 3
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.

Constraints:

  • m == grid.length

  • n == grid[i].length

  • 1 ⇐ m ⇐ 250

  • 1 ⇐ n ⇐ 250

  • grid[i][j] == 0 or 1

1
Unresolved directive in 1267-count-servers-that-communicate.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1267_CountServersThatCommunicate.java[]

1268. Search Suggestions System

Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

Return list of lists of the suggested products after each character of searchWord is typed.

Example 1:

Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]

Example 2:

Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

Example 3:

Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

Example 4:

Input: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]

Constraints:

  • 1 ⇐ products.length ⇐ 1000

  • There are no repeated elements in products.

  • 1 ⇐ Σ products[i].length ⇐ 2 * 10^4

  • All characters of products[i] are lower-case English letters.

  • 1 ⇐ searchWord.length ⇐ 1000

  • All characters of searchWord are lower-case English letters.

1
Unresolved directive in 1268-search-suggestions-system.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1268_SearchSuggestionsSystem.java[]

1269. Number of Ways to Stay in the Same Place After Some Steps

You have a pointer at index 0 in an array of size <font face="monospace">arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array or stay in the same place (The pointer should not be placed outside the array at any time).

Given two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after *exactly *<font face="monospace">steps steps.

Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

Input: steps = 3, arrLen = 2
Output: 4
Explanation: There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay

Example 2:

Input: steps = 2, arrLen = 4
Output: 2
Explanation: There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay

Example 3:

Input: steps = 4, arrLen = 2
Output: 8

Constraints:

  • 1 ⇐ steps ⇐ 500

  • 1 ⇐ arrLen ⇐ 10^6

1
Unresolved directive in 1269-number-of-ways-to-stay-in-the-same-place-after-some-steps.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1269_NumberOfWaysToStayInTheSamePlaceAfterSomeSteps.java[]

1270. All People Report to the Given Manager

1
Unresolved directive in 1270-all-people-report-to-the-given-manager.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1270_AllPeopleReportToTheGivenManager.java[]

1271. Hexspeak

1
Unresolved directive in 1271-hexspeak.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1271_Hexspeak.java[]

1272. Remove Interval

1
Unresolved directive in 1272-remove-interval.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1272_RemoveInterval.java[]

1273. Delete Tree Nodes

1
Unresolved directive in 1273-delete-tree-nodes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1273_DeleteTreeNodes.java[]

1274. Number of Ships in a Rectangle

1
Unresolved directive in 1274-number-of-ships-in-a-rectangle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1274_NumberOfShipsInARectangle.java[]

1275. Find Winner on a Tic Tac Toe Game

Tic-tac-toe is played by two players A and B on a 3 x 3 grid.

Here are the rules of Tic-Tac-Toe:

  • Players take turns placing characters into empty squares (" ").

  • The first player A always places "X" characters, while the second player B always places "O" characters.

  • "X" and "O" characters are always placed into empty squares, never on filled ones.

  • The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal.

  • The game also ends if all squares are non-empty.

  • No more moves can be played if the game is over.

Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play.

Return the winner of the game if it exists (A or B), in case the game ends in a draw return "Draw", if there are still movements to play return "Pending".

You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first.

Example 1:

Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]
Output: "A"
Explanation: "A" wins, he always plays first.
"X  "    "X  "    "X  "    "X  "    "X  "
"   " -> "   " -> " X " -> " X " -> " X "
"   "    "O  "    "O  "    "OO "    "OO*X*"

Example 2:

Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]
Output: "B"
Explanation: "B" wins.
"X  "    "X  "    "XX "    "XXO"    "XXO"    "XX*O*"
"   " -> " O " -> " O " -> " O " -> "XO " -> "X*O* "
"   "    "   "    "   "    "   "    "   "    "O  "

Example 3:

Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]
Output: "Draw"
Explanation: The game ends in a draw since there are no moves to make.
"XXO"
"OOX"
"XOX"

Example 4:

Input: moves = [[0,0],[1,1]]
Output: "Pending"
Explanation: The game has not finished yet.
"X  "
" O "
"   "

Constraints:

  • 1 ⇐ moves.length ⇐ 9

  • moves[i].length == 2

  • 0 ⇐ moves[i][j] ⇐ 2

  • There are no repeated elements on moves.

  • moves follow the rules of tic tac toe.

1
Unresolved directive in 1275-find-winner-on-a-tic-tac-toe-game.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1275_FindWinnerOnATicTacToeGame.java[]

1276. Number of Burgers with No Waste of Ingredients

Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:

  • Jumbo Burger: 4 tomato slices and 1 cheese slice.

  • Small Burger: 2 Tomato slices and 1 cheese slice.

Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].

Example 1:

Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 41 + 26 = 16 tomato and 1 + 6 = 7 cheese. There will be no remaining ingredients.

Example 2:

Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.

Example 3:

Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.

Example 4:

Input: tomatoSlices = 0, cheeseSlices = 0
Output: [0,0]

Example 5:

Input: tomatoSlices = 2, cheeseSlices = 1
Output: [0,1]

Constraints:

  • 0 ⇐ tomatoSlices ⇐ 10^7

  • 0 ⇐ cheeseSlices ⇐ 10^7

1
Unresolved directive in 1276-number-of-burgers-with-no-waste-of-ingredients.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1276_NumberOfBurgersWithNoWasteOfIngredients.java[]

1277. Count Square Submatrices with All Ones

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

Example 1:

Input: matrix =
[
  [0,1,1,1],
  [1,1,1,1],
  [0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is  1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.

Example 2:

Input: matrix =
[
  [1,0,1],
  [1,1,0],
  [1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.

Constraints:

  • 1 ⇐ arr.length ⇐ 300

  • 1 ⇐ arr[0].length ⇐ 300

  • 0 ⇐ arr[i][j] ⇐ 1

1
Unresolved directive in 1277-count-square-submatrices-with-all-ones.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1277_CountSquareSubmatricesWithAllOnes.java[]

1278. Palindrome Partitioning III

You are given a string s containing lowercase letters and an integer k. You need to :

  • First, change some characters of s to other lowercase English letters.

  • Then divide s into k non-empty disjoint substrings such that each substring is palindrome.

Return the minimal number of characters that you need to change to divide the string.

Example 1:

Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.

Example 2:

Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.

Example 3:

Input: s = "leetcode", k = 8
Output: 0

Constraints:

  • 1 ⇐ k ⇐ s.length ⇐ 100.

  • s only contains lowercase English letters.

1
Unresolved directive in 1278-palindrome-partitioning-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1278_PalindromePartitioningIII.java[]

1279. Traffic Light Controlled Intersection

1
Unresolved directive in 1279-traffic-light-controlled-intersection.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1279_TrafficLightControlledIntersection.java[]

1280. Students and Examinations

1
Unresolved directive in 1280-students-and-examinations.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1280_StudentsAndExaminations.java[]

1281. Subtract the Product and Sum of Digits of an Integer

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Example 1:

Input: n = 234
Output: 15
Explanation:
Product of digits = 2  3  4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15

Example 2:

Input: n = 4421
Output: 21
Explanation:
Product of digits = 4  4  2 * 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21

Constraints:

  • 1 ⇐ n ⇐ 10^5

1
Unresolved directive in 1281-subtract-the-product-and-sum-of-digits-of-an-integer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1281_SubtractTheProductAndSumOfDigitsOfAnInteger.java[]

1282. Group the People Given the Group Size They Belong To

There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people’s IDs each group includes.

You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution.

Example 1:

Input: groupSizes = [3,3,3,3,3,1,3]
Output: [[5],[0,1,2],[3,4,6]]
Explanation:
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

Example 2:

Input: groupSizes = [2,1,3,3,3,2]
Output: [[1],[0,5],[2,3,4]]

Constraints:

  • groupSizes.length == n

  • 1 ⇐ n ⇐ 500

  • 1 ⇐ groupSizes[i] ⇐ n

1
Unresolved directive in 1282-group-the-people-given-the-group-size-they-belong-to.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1282_GroupThePeopleGivenTheGroupSizeTheyBelongTo.java[]

1283. Find the Smallest Divisor Given a Threshold

Given an array of integers nums and an integer threshold, we will choose a positive integer divisor and divide all the array by it and sum the result of the division. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.

Each result of division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).

It is guaranteed that there will be an answer.

Example 1:

Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).

Example 2:

Input: nums = [2,3,5,7,11], threshold = 11
Output: 3

Example 3:

Input: nums = [19], threshold = 5
Output: 4

Constraints:

  • 1 ⇐ nums.length ⇐ 5 * 10^4

  • 1 ⇐ nums[i] ⇐ 10^6

  • nums.length ⇐ threshold ⇐ 10^6

1
Unresolved directive in 1283-find-the-smallest-divisor-given-a-threshold.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1283_FindTheSmallestDivisorGivenAThreshold.java[]

1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix

Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbours of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighboors if they share one edge.

Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.

Binary matrix is a matrix with all cells equal to 0 or 1 only.

Zero matrix is a matrix with all cells equal to 0.

Example 1:

matrix
Input: mat = [[0,0],[0,1]]
Output: 3
Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.

Example 2:

Input: mat = [[0]]
Output: 0
Explanation: Given matrix is a zero matrix. We don't need to change it.

Example 3:

Input: mat = [[1,1,1],[1,0,1],[0,0,0]]
Output: 6

Example 4:

Input: mat = [[1,0,0],[1,0,0]]
Output: -1
Explanation: Given matrix can't be a zero matrix

Constraints:

  • m == mat.length

  • n == mat[0].length

  • 1 ⇐ m ⇐ 3

  • 1 ⇐ n ⇐ 3

  • mat[i][j] is 0 or 1.

1
Unresolved directive in 1284-minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1284_MinimumNumberOfFlipsToConvertBinaryMatrixToZeroMatrix.java[]

1285. Find the Start and End Number of Continuous Ranges

1
Unresolved directive in 1285-find-the-start-and-end-number-of-continuous-ranges.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1285_FindTheStartAndEndNumberOfContinuousRanges.java[]

1286. Iterator for Combination

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:

CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.

iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false

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.

1
Unresolved directive in 1286-iterator-for-combination.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1286_IteratorForCombination.java[]

1287. Element Appearing More Than 25% In Sorted Array

Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.

Return that integer.

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6

Constraints:

  • 1 ⇐ arr.length ⇐ 10^4

  • 0 ⇐ arr[i] ⇐ 10^5

1
Unresolved directive in 1287-element-appearing-more-than-25-in-sorted-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1287_ElementAppearingMoreThan25InSortedArray.java[]

1288. Remove Covered Intervals

Given a list of intervals, remove all intervals that are covered by another interval in the list. Interval [a,b) is covered by interval [c,d) if and only if c ⇐ a and b ⇐ d.

After doing so, return the number of remaining intervals.

Example 1:

Input: intervals = [[1,4],[3,6],[2,8]]
Output: 2
Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.

Constraints:

  • 1 ⇐ intervals.length ⇐ 1000

  • 0 ⇐ intervals[i][0] < intervals[i][1] ⇐ 10^5

  • intervals[i] != intervals[j] for all i != j

1
Unresolved directive in 1288-remove-covered-intervals.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1288_RemoveCoveredIntervals.java[]

1289. Minimum Falling Path Sum II

Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.

Return the minimum sum of a falling path with non-zero shifts.

Example 1:

Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.

Constraints:

  • 1 ⇐ arr.length == arr[i].length ⇐ 200

  • -99 ⇐ arr[i][j] ⇐ 99

1
Unresolved directive in 1289-minimum-falling-path-sum-ii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1289_MinimumFallingPathSumII.java[]

1290. Convert Binary Number in a Linked List to Integer

Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.

Return the decimal value of the number in the linked list.

Example 1:

graph 1
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

Example 2:

Input: head = [0]
Output: 0

Example 3:

Input: head = [1]
Output: 1

Example 4:

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880

Example 5:

Input: head = [0,0]
Output: 0

Constraints:

  • The Linked List is not empty.

  • Number of nodes will not exceed 30.

  • Each node’s value is either 0 or 1.

1
Unresolved directive in 1290-convert-binary-number-in-a-linked-list-to-integer.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1290_ConvertBinaryNumberInALinkedListToInteger.java[]

1291. Sequential Digits

An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

Example 1:

Input: low = 100, high = 300
Output: [123,234]

Example 2:

Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]

Constraints:

  • 10 ⇐ low ⇐ high ⇐ 10^9

1
Unresolved directive in 1291-sequential-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1291_SequentialDigits.java[]

1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.

Example 1:

e1
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.

Example 2:

Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0

Example 3:

Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
Output: 3

Example 4:

Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
Output: 2

Constraints:

  • 1 ⇐ m, n ⇐ 300

  • m == mat.length

  • n == mat[i].length

  • 0 ⇐ mat[i][j] ⇐ 10000

  • 0 ⇐ threshold ⇐ 10^5

1
Unresolved directive in 1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1292_MaximumSideLengthOfASquareWithSumLessThanOrEqualToThreshold.java[]

1293. Shortest Path in a Grid with Obstacles Elimination

Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In one step, you can move up, down, left or right from and to an empty cell.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m-1, n-1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

Example 1:

Input:
grid =
[[0,0,0],
 [1,1,0],
 [0,0,0],
 [0,1,1],
 [0,0,0]],
k = 1
Output: 6
Explanation:
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Example 2:

Input:
grid =
[[0,1,1],
 [1,1,1],
 [1,0,0]],
k = 1
Output: -1
Explanation:
We need to eliminate at least two obstacles to find such a walk.

Constraints:

  • grid.length == m

  • grid[0].length == n

  • 1 ⇐ m, n ⇐ 40

  • 1 ⇐ k ⇐ m*n

  • grid[i][j] == 0 or 1

  • grid[0][0] == grid[m-1][n-1] == 0

1
Unresolved directive in 1293-shortest-path-in-a-grid-with-obstacles-elimination.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1293_ShortestPathInAGridWithObstaclesElimination.java[]

1294. Weather Type in Each Country

1
Unresolved directive in 1294-weather-type-in-each-country.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1294_WeatherTypeInEachCountry.java[]

1295. Find Numbers with Even Number of Digits

Given an array nums of integers, return how many of them contain an even number of digits.

Example 1:

Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.

Example 2:

Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.

Constraints:

  • 1 ⇐ nums.length ⇐ 500

  • 1 ⇐ nums[i] ⇐ 10^5

1
Unresolved directive in 1295-find-numbers-with-even-number-of-digits.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1295_FindNumbersWithEvenNumberOfDigits.java[]

1296. Divide Array in Sets of K Consecutive Numbers

Given an array of integers nums and a positive integer k, find whether it’s possible to divide this array into sets of k consecutive numbers

Return True if its possible* *otherwise return False.

Example 1:

Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].

Example 2:

Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].

Example 3:

Input: nums = [3,3,2,2,1,1], k = 3
Output: true

Example 4:

Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.

Constraints:

  • 1 ⇐ nums.length ⇐ 10^5

  • 1 ⇐ nums[i] ⇐ 10^9

  • 1 ⇐ k ⇐ nums.length

1
Unresolved directive in 1296-divide-array-in-sets-of-k-consecutive-numbers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1296_DivideArrayInSetsOfKConsecutiveNumbers.java[]

1297. Maximum Number of Occurrences of a Substring

Given a string s, return the maximum number of ocurrences of any substring under the following rules:

  • The number of unique characters in the substring must be less than or equal to maxLetters.

  • The substring size must be between minSize and maxSize inclusive.

Example 1:

Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).

Example 2:

Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.

Example 3:

Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3
Output: 3

Example 4:

Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
Output: 0

Constraints:

  • 1 ⇐ s.length ⇐ 10^5

  • 1 ⇐ maxLetters ⇐ 26

  • 1 ⇐ minSize ⇐ maxSize ⇐ min(26, s.length)

  • s only contains lowercase English letters.

1
Unresolved directive in 1297-maximum-number-of-occurrences-of-a-substring.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1297_MaximumNumberOfOccurrencesOfASubstring.java[]

1298. Maximum Candies You Can Get from Boxes

Given n boxes, each box is given in the format [status, candies, keys, containedBoxes] where:

  • status[i]: an integer which is 1 if box[i] is open and 0 if box[i] is closed.

  • candies[i]: an integer representing the number of candies in box[i].

  • keys[i]: an array contains the indices of the boxes you can open with the key in box[i].

  • containedBoxes[i]: an array contains the indices of the boxes found in box[i].

You will start with some boxes given in initialBoxes array. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.

Return the maximum number of candies you can get following the rules above.

Example 1:

Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output: 16
Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you don't have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.

Example 2:

Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]
Output: 6
Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.

Example 3:

Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
Output: 1

Example 4:

Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
Output: 0

Example 5:

Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
Output: 7

Constraints:

  • 1 ⇐ status.length ⇐ 1000

  • status.length == candies.length == keys.length == containedBoxes.length == n

  • status[i] is 0 or 1.

  • 1 ⇐ candies[i] ⇐ 1000

  • <font face="monospace">0 ⇐ keys[i].length ⇐ status.length

  • 0 ⇐ keys[i][j] < status.length

  • All values in keys[i] are unique.

  • <font face="monospace">0 ⇐ containedBoxes<font face="monospace">[i].length ⇐ status.length

  • 0 ⇐ containedBoxes[i][j] < status.length

  • All values in containedBoxes[i] are unique.

  • Each box is contained in one box at most.

  • 0 ⇐ initialBoxes.length ⇐ status.length

  • <font face="monospace">0 ⇐ initialBoxes[i] < status.length

1
Unresolved directive in 1298-maximum-candies-you-can-get-from-boxes.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1298_MaximumCandiesYouCanGetFromBoxes.java[]

1299. Replace Elements with Greatest Element on Right Side

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Example 1:

Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]

Constraints:

  • 1 ⇐ arr.length ⇐ 10^4

  • 1 ⇐ arr[i] ⇐ 10^5

1
Unresolved directive in 1299-replace-elements-with-greatest-element-on-right-side.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1299_ReplaceElementsWithGreatestElementOnRightSide.java[]

1300. Sum of Mutated Array Closest to Target

Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.

In case of a tie, return the minimum such integer.

Notice that the answer is not neccesarilly a number from arr.

Example 1:

Input: arr = [4,9,3], target = 10
Output: 3
Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.

Example 2:

Input: arr = [2,3,5], target = 10
Output: 5

Example 3:

Input: arr = [60864,25176,27249,21296,20204], target = 56803
Output: 11361

Constraints:

  • 1 ⇐ arr.length ⇐ 10^4

  • 1 ⇐ arr[i], target ⇐ 10^5

1
Unresolved directive in 1300-sum-of-mutated-array-closest-to-target.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1300_SumOfMutatedArrayClosestToTarget.java[]

1301. Number of Paths with Max Score

You are given a square board of characters. You can move on the board starting at the bottom right square marked with the character 'S'.

You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, …​, 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.

Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.

In case there is no path, return [0, 0].

Example 1:

Input: board = ["E23","2X2","12S"]
Output: [7,1]

Example 2:

Input: board = ["E12","1X1","21S"]
Output: [4,2]

Example 3:

Input: board = ["E11","XXX","11S"]
Output: [0,0]

Constraints:

  • 2 ⇐ board.length == board[i].length ⇐ 100

1
Unresolved directive in 1301-number-of-paths-with-max-score.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1301_NumberOfPathsWithMaxScore.java[]

1302. Deepest Leaves Sum

Given a binary tree, return the sum of values of its deepest leaves.

Example 1:

image::https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png[]

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.

  • The value of nodes is between 1 and 100.

1
Unresolved directive in 1302-deepest-leaves-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1302_DeepestLeavesSum.java[]

1303. Find the Team Size

1
Unresolved directive in 1303-find-the-team-size.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1303_FindTheTeamSize.java[]

1304. Find N Unique Integers Sum up to Zero

Given an integer n, return any array containing n unique integers such that they add up to 0.

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3
Output: [-1,0,1]

Example 3:

Input: n = 1
Output: [0]

Constraints:

  • 1 ⇐ n ⇐ 1000

1
Unresolved directive in 1304-find-n-unique-integers-sum-up-to-zero.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1304_FindNUniqueIntegersSumUpToZero.java[]

1305. All Elements in Two Binary Search Trees

Given two binary search trees root1 and root2.

Return a list containing all the integers from both trees sorted in ascending order.

Example 1:

q2 e1
Input: root1 = [2,1,4], root2 = [1,0,3]
Output: [0,1,1,2,3,4]

Example 2:

Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
Output: [-10,0,0,1,2,5,7,10]

Example 3:

Input: root1 = [], root2 = [5,1,7,0,2]
Output: [0,1,2,5,7]

Example 4:

Input: root1 = [0,-10,10], root2 = []
Output: [-10,0,10]

Example 5:

q2 e5
Input: root1 = [1,null,8], root2 = [8,1]
Output: [1,1,8,8]

Constraints:

  • Each tree has at most 5000 nodes.

  • Each node’s value is between [-10^5, 10^5].

1
Unresolved directive in 1305-all-elements-in-two-binary-search-trees.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1305_AllElementsInTwoBinarySearchTrees.java[]

1306. Jump Game III

Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.

Notice that you can not jump outside of the array at any time.

Example 1:

Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
All possible ways to reach at index 3 with value 0 are:
index 5 -> index 4 -> index 1 -> index 3
index 5 -> index 6 -> index 4 -> index 1 -> index 3

Example 2:

Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
One possible way to reach at index 3 with value 0 is:
index 0 -> index 4 -> index 1 -> index 3

Example 3:

Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: There is no way to reach at index 1 with value 0.

Constraints:

  • 1 ⇐ arr.length ⇐ 5 * 10^4

  • 0 ⇐ arr[i] < arr.length

  • 0 ⇐ start < arr.length

1
Unresolved directive in 1306-jump-game-iii.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1306_JumpGameIII.java[]

1307. Verbal Arithmetic Puzzle

Given an equation, represented by words on left side and the result on right side.

You need to check if the equation is solvable under the following rules:

  • Each character is decoded as one digit (0 - 9).

  • Every pair of different characters they must map to different digits.

  • Each words[i] and result are decoded as one number without leading zeros.

  • Sum of numbers on left side (words) will equal to the number on right side (result).

Return True if the equation is solvable otherwise return False.

Example 1:

Input: words = ["SEND","MORE"], result = "MONEY"
Output: true
Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'
Such that: "SEND" + "MORE" = "MONEY" ,  9567 + 1085 = 10652

Example 2:

Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
Output: true
Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4
Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" ,  650 + 68782 + 68782 = 138214

Example 3:

Input: words = ["THIS","IS","TOO"], result = "FUNNY"
Output: true

Example 4:

Input: words = ["LEET","CODE"], result = "POINT"
Output: false

Constraints:

  • 2 ⇐ words.length ⇐ 5

  • 1 ⇐ words[i].length, result.length ⇐ 7

  • words[i], result contains only upper case English letters.

  • Number of different characters used on the expression is at most 10.

1
Unresolved directive in 1307-verbal-arithmetic-puzzle.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1307_VerbalArithmeticPuzzle.java[]

1308. Running Total for Different Genders

1
Unresolved directive in 1308-running-total-for-different-genders.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1308_RunningTotalForDifferentGenders.java[]

1309. Decrypt String from Alphabet to Integer Mapping

Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:

  • Characters ('a' to 'i') are represented by ('1' to '9') respectively.

  • Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.

Return the string formed after mapping.

It’s guaranteed that a unique mapping will always exist.

Example 1:

Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

Example 2:

Input: s = "1326#"
Output: "acz"

Example 3:

Input: s = "25#"
Output: "y"

Example 4:

Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
Output: "abcdefghijklmnopqrstuvwxyz"

Constraints:

  • 1 ⇐ s.length ⇐ 1000

  • s[i] only contains digits letters ('0'-'9') and '#' letter.

  • s will be valid string such that mapping is always possible.

1
Unresolved directive in 1309-decrypt-string-from-alphabet-to-integer-mapping.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1309_DecryptStringFromAlphabetToIntegerMapping.java[]

1310. XOR Queries of a Subarray

Given the array arr of positive integers and the array queries where queries[i] = [L~i, Ri~], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor …​ xor arr[Ri] ). Return an array containing the result for the given queries.

Example 1:

Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
Output: [2,7,14,8]
Explanation:
The binary representation of the elements in the array are:
1 = 0001
3 = 0011
4 = 0100
8 = 1000
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8

Example 2:

Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
Output: [8,0,4,4]

Constraints:

  • 1 ⇐ arr.length ⇐ 3 * 10^4

  • 1 ⇐ arr[i] ⇐ 10^9

  • 1 ⇐ queries.length ⇐ 3 * 10^4

  • queries[i].length == 2

  • 0 ⇐ queries[i][0] ⇐ queries[i][1] < arr.length

1
Unresolved directive in 1310-xor-queries-of-a-subarray.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1310_XORQueriesOfASubarray.java[]

1311. Get Watched Videos by Your Friends

There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.

Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.

Example 1:

leetcode friends 1
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1
Output: ["B","C"]
Explanation:
You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):
Person with id = 1 -> watchedVideos = ["C"]
Person with id = 2 -> watchedVideos = ["B","C"]
The frequencies of watchedVideos by your friends are:
B -> 1
C -> 2

Example 2:

leetcode friends 2
Input: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2
Output: ["D"]
Explanation:
You have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).

Constraints:

  • n == watchedVideos.length == friends.length

  • 2 ⇐ n ⇐ 100

  • 1 ⇐ watchedVideos[i].length ⇐ 100

  • 1 ⇐ watchedVideos[i][j].length ⇐ 8

  • 0 ⇐ friends[i].length < n

  • 0 ⇐ friends[i][j] < n

  • 0 ⇐ id < n

  • 1 ⇐ level < n

  • if friends[i] contains j, then friends[j] contains i

1
Unresolved directive in 1311-get-watched-videos-by-your-friends.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1311_GetWatchedVideosByYourFriends.java[]

1312. Minimum Insertion Steps to Make a String Palindrome

Given a string s. In one step you can insert any character at any index of the string.

Return the minimum number of steps to make s palindrome.

A Palindrome String is one that reads the same backward as well as forward.

Example 1:

Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we don't need any insertions.

Example 2:

Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".

Example 3:

Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".

Example 4:

Input: s = "g"
Output: 0

Example 5:

Input: s = "no"
Output: 1

Constraints:

  • 1 ⇐ s.length ⇐ 500

  • All characters of s are lower case English letters.

1
Unresolved directive in 1312-minimum-insertion-steps-to-make-a-string-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1312_MinimumInsertionStepsToMakeAStringPalindrome.java[]

1313. Decompress Run-Length Encoded List

We are given a list nums of integers representing a list compressed with run-length encoding.

Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are a elements with value b in the decompressed list.

Return the decompressed list.

Example 1:

Input: nums = [1,2,3,4]
Output: [2,4,4,4]
Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].
The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].
At the end the concatenation [2] + [4,4,4,4] is [2,4,4,4].

Constraints:

  • 2 ⇐ nums.length ⇐ 100

  • nums.length % 2 == 0

  • <font face="monospace">1 ⇐ nums[i] ⇐ 100

1
Unresolved directive in 1313-decompress-run-length-encoded-list.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1313_DecompressRunLengthEncodedList.java[]

1314. Matrix Block Sum

Given a m * n matrix mat and an integer K, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for i - K ⇐ r ⇐ i + K, j - K ⇐ c ⇐ j + K, and (r, c) is a valid position in the matrix.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]

Example 2:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]

Constraints:

  • m == mat.length

  • n == mat[i].length

  • 1 ⇐ m, n, K ⇐ 100

  • 1 ⇐ mat[i][j] ⇐ 100

1
Unresolved directive in 1314-matrix-block-sum.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1314_MatrixBlockSum.java[]

1315. Sum of Nodes with Even-Valued Grandparent

Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)

If there are no nodes with an even-valued grandparent, return 0.

Example 1:

1473 ex1
Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.

  • The value of nodes is between 1 and 100.

1
Unresolved directive in 1315-sum-of-nodes-with-even-valued-grandparent.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1315_SumOfNodesWithEvenValuedGrandparent.java[]

1316. Distinct Echo Substrings

Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).

Example 1:

Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Example 2:

Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".

Constraints:

  • 1 ⇐ text.length ⇐ 2000

  • text has only lowercase English letters.

1
Unresolved directive in 1316-distinct-echo-substrings.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1316_DistinctEchoSubstrings.java[]

1317. Convert Integer to the Sum of Two No-Zero Integers

Given an integer n. No-Zero integer is a positive integer which doesn’t contain any 0 in its decimal representation.

Return a list of two integers [A, B] where:

  • A and B are No-Zero integers.

  • A + B = n

It’s guarateed that there is at least one valid solution. If there are many valid solutions you can return any of them.

Example 1:

Input: n = 2
Output: [1,1]
Explanation: A = 1, B = 1. A + B = n and both A and B don't contain any 0 in their decimal representation.

Example 2:

Input: n = 11
Output: [2,9]

Example 3:

Input: n = 10000
Output: [1,9999]

Example 4:

Input: n = 69
Output: [1,68]

Example 5:

Input: n = 1010
Output: [11,999]

Constraints:

  • 2 ⇐ n ⇐ 10^4

1
Unresolved directive in 1317-convert-integer-to-the-sum-of-two-no-zero-integers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1317_ConvertIntegerToTheSumOfTwoNoZeroIntegers.java[]

1318. Minimum Flips to Make a OR b Equal to c

Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).

Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.

Example 1:

sample 3 1676
Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)

Example 2:

Input: a = 4, b = 2, c = 7
Output: 1

Example 3:

Input: a = 1, b = 2, c = 3
Output: 0

Constraints:

  • 1 ⇐ a ⇐ 10^9

  • 1 ⇐ b ⇐ 10^9

  • 1 ⇐ c ⇐ 10^9

1
Unresolved directive in 1318-minimum-flips-to-make-a-or-b-equal-to-c.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1318_MinimumFlipsToMakeAORBEqualToC.java[]

1319. Number of Operations to Make Network Connected

There are n computers numbered from 0 to n-1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.

Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it’s not possible, return -1.

Example 1:

sample 1 1677
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.

Example 2:

sample 2 1677
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2

Example 3:

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.

Example 4:

Input: n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
Output: 0

Constraints:

  • 1 ⇐ n ⇐ 10^5

  • 1 ⇐ connections.length ⇐ min(n*(n-1)/2, 10^5)

  • connections[i].length == 2

  • 0 ⇐ connections[i][0], connections[i][1] < n

  • connections[i][0] != connections[i][1]

  • There are no repeated connections.

  • No two computers are connected by more than one cable.

1
Unresolved directive in 1319-number-of-operations-to-make-network-connected.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1319_NumberOfOperationsToMakeNetworkConnected.java[]

1320. Minimum Distance to Type a Word Using Two Fingers

leetcode keyboard

You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for example, the letter A is located at coordinate (0,0), the letter B is located at coordinate (0,1), the letter P is located at coordinate (2,3) and the letter Z is located at coordinate (4,1).

Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates (x1,y1) and (x2,y2) is |x1 - x2| + |y1 - y2|.

Note that the initial positions of your two fingers are considered free so don’t count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.

Example 1:

Input: word = "CAKE"
Output: 3
Explanation:
Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3

Example 2:

Input: word = "HAPPY"
Output: 6
Explanation:
Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6

Example 3:

Input: word = "NEW"
Output: 3

Example 4:

Input: word = "YEAR"
Output: 7

Constraints:

  • 2 ⇐ word.length ⇐ 300

  • Each <code data-stringify-type="code">word[i]` is an English uppercase letter.

1
Unresolved directive in 1320-minimum-distance-to-type-a-word-using-two-fingers.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1320_MinimumDistanceToTypeAWordUsingTwoFingers.java[]

1321. Restaurant Growth

1
Unresolved directive in 1321-restaurant-growth.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1321_RestaurantGrowth.java[]

1322. Ads Performance

1
Unresolved directive in 1322-ads-performance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1322_AdsPerformance.java[]

1323. Maximum 69 Number

Given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

Example 1:

Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.

Example 2:

Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.

Constraints:

  • 1 ⇐ num ⇐ 10^4

  • `num’s digits are 6 or 9.

1
Unresolved directive in 1323-maximum-69-number.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1323_Maximum69Number.java[]

1324. Print Words Vertically

Given a string s. Return all the words vertically in the same order in which they appear in s.

Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).

Each word would be put on only one column and that in one column there will be only one word.

Example 1:

Input: s = "HOW ARE YOU"
Output: ["HAY","ORO","WEU"]
Explanation: Each word is printed vertically.
 "HAY"
 "ORO"
 "WEU"

Example 2:

Input: s = "TO BE OR NOT TO BE"
Output: ["TBONTB","OEROOE","   T"]
Explanation: Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
"   T"

Example 3:

Input: s = "CONTEST IS COMING"
Output: ["CIC","OSO","N M","T I","E N","S G","T"]

Constraints:

  • 1 ⇐ s.length ⇐ 200

  • s contains only upper case English letters.

  • It’s guaranteed that there is only one space between 2 words.

1
Unresolved directive in 1324-print-words-vertically.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1324_PrintWordsVertically.java[]

1325. Delete Leaves With a Given Value

Given a binary tree root and an integer target, delete all the leaf nodes with value target.

Note that once you delete a leaf node with value target*, *if it’s parent node becomes a leaf node and has the value <font face="monospace">target, it should also be deleted (you need to continue doing that until you can’t).

Example 1:

sample 1 1684
Input: root = [1,2,3,2,null,2,4], target = 2
Output: [1,null,3,null,4]
Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left).
After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).

Example 2:

sample 2 1684
Input: root = [1,3,3,3,2], target = 3
Output: [1,3,null,null,2]

Example 3:

sample 3 1684
Input: root = [1,2,null,2,null,2], target = 2
Output: [1]
Explanation: Leaf nodes in green with value (target = 2) are removed at each step.

Example 4:

Input: root = [1,1,1], target = 1
Output: []

Example 5:

Input: root = [1,2,3], target = 1
Output: [1,2,3]

Constraints:

  • 1 ⇐ target ⇐ 1000

  • Each tree has at most 3000 nodes.

  • Each node’s value is between [1, 1000].

1
Unresolved directive in 1325-delete-leaves-with-a-given-value.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1325_DeleteLeavesWithAGivenValue.java[]

1326. Minimum Number of Taps to Open to Water a Garden

There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).

There are n + 1 taps located at points [0, 1, …​, n] in the garden.

Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.

Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.

Example 1:

1685 example 1
Input: n = 5, ranges = [3,4,1,1,0,0]
Output: 1
Explanation: The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]

Example 2:

Input: n = 3, ranges = [0,0,0,0]
Output: -1
Explanation: Even if you activate all the four taps you cannot water the whole garden.

Example 3:

Input: n = 7, ranges = [1,2,1,0,2,1,0,1]
Output: 3

Example 4:

Input: n = 8, ranges = [4,0,0,0,0,0,0,0,4]
Output: 2

Example 5:

Input: n = 8, ranges = [4,0,0,0,4,0,0,0,4]
Output: 1

Constraints:

  • 1 ⇐ n ⇐ 10^4

  • ranges.length == n + 1

  • 0 ⇐ ranges[i] ⇐ 100

1
Unresolved directive in 1326-minimum-number-of-taps-to-open-to-water-a-garden.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1326_MinimumNumberOfTapsToOpenToWaterAGarden.java[]

1327. List the Products Ordered in a Period

1
Unresolved directive in 1327-list-the-products-ordered-in-a-period.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1327_ListTheProductsOrderedInAPeriod.java[]

1328. Break a Palindrome

Given a palindromic string palindrome, replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn’t a palindrome.

After doing so, return the final string. If there is no way to do so, return the empty string.

Example 1:

Input: palindrome = "abccba"
Output: "aaccba"

Example 2:

Input: palindrome = "a"
Output: ""

Constraints:

  • 1 ⇐ palindrome.length ⇐ 1000

  • palindrome consists of only lowercase English letters.

1
Unresolved directive in 1328-break-a-palindrome.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1328_BreakAPalindrome.java[]

1329. Sort the Matrix Diagonally

Given a m * n matrix mat of integers, sort it diagonally in ascending order from the top-left to the bottom-right then return the sorted array.

Example 1:

1482 example 1 2
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]

Constraints:

  • m == mat.length

  • n == mat[i].length

  • 1 ⇐ m, n ⇐ 100

  • 1 ⇐ mat[i][j] ⇐ 100

1
Unresolved directive in 1329-sort-the-matrix-diagonally.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1329_SortTheMatrixDiagonally.java[]

1330. Reverse Subarray To Maximize Array Value

You are given an integer array nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all 0 ⇐ i < nums.length-1.

You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.

Find maximum possible value of the final array.

Example 1:

Input: nums = [2,3,1,5,4]
Output: 10
Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.

Example 2:

Input: nums = [2,4,9,24,2,1,10]
Output: 68

Constraints:

  • 1 ⇐ nums.length ⇐ 3*10^4

  • -10^5 ⇐ nums[i] ⇐ 10^5

1
Unresolved directive in 1330-reverse-subarray-to-maximize-array-value.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1330_ReverseSubarrayToMaximizeArrayValue.java[]

1331. Rank Transform of an Array

Given an array of integers arr, replace each element with its rank.

The rank represents how large the element is. The rank has the following rules:

  • Rank is an integer starting from 1.

  • The larger the element, the larger the rank. If two elements are equal, their rank must be the same.

  • Rank should be as small as possible.

Example 1:

Input: arr = [40,10,20,30]
Output: [4,1,2,3]
Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.

Example 2:

Input: arr = [100,100,100]
Output: [1,1,1]
Explanation: Same elements share the same rank.

Example 3:

Input: arr = [37,12,28,9,100,56,80,5,12]
Output: [5,3,4,2,8,6,7,1,3]

Constraints:

  • 0 ⇐ arr.length ⇐ 105

  • -109 ⇐ arr[i] ⇐ 109

1
Unresolved directive in 1331-rank-transform-of-an-array.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1331_RankTransformOfAnArray.java[]

1332. Remove Palindromic Subsequences

Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.

Return the minimum number of steps to make the given string empty.

A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.

A string is called palindrome if is one that reads the same backward as well as forward.

Example 1:

Input: s = "ababa"
Output: 1
Explanation: String is already palindrome

Example 2:

Input: s = "abb"
Output: 2
Explanation: "a*bb" -> "*bb" -> "".
Remove palindromic subsequence "a" then "bb".

Example 3:

Input: s = "baabb"
Output: 2
Explanation: "baa*b*b" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".

Example 4:

Input: s = ""
Output: 0

Constraints:

  • 0 ⇐ s.length ⇐ 1000

  • s only consists of letters 'a' and 'b'

1
Unresolved directive in 1332-remove-palindromic-subsequences.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1332_RemovePalindromicSubsequences.java[]

1333. Filter Restaurants by Vegan-Friendly, Price and Distance

Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.

The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.

Return the array of restaurant *IDs* after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by *id* from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.

Example 1:

Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10
Output: [3,1,5]
Explanation:
The restaurants are:
Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]
Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]
Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]
Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]
Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1]
After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest).

Example 2:

Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10
Output: [4,3,2,1,5]
Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.

Example 3:

Input: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3
Output: [4,5]

Constraints:

  • 1 ⇐ restaurants.length ⇐ 10^4

  • restaurants[i].length == 5

  • 1 ⇐ idi, ratingi, pricei, distance~i ~⇐ 10^5

  • 1 ⇐ maxPrice, maxDistance ⇐ 10^5

  • veganFriendlyi and veganFriendly are 0 or 1.

  • All idi are distinct.

1
Unresolved directive in 1333-filter-restaurants-by-vegan-friendly-price-and-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1333_FilterRestaurantsByVeganFriendlyPriceAndDistance.java[]

1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance

There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.

Return the city with the smallest number* of cities that are reachable through some path and whose distance is *at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.

Notice that the distance of a path connecting cities *i* and *j* is equal to the sum of the edges' weights along that path.

Example 1:

find the city 01
Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
Output: 3
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -> [City 1, City 2]
City 1 -> [City 0, City 2, City 3]
City 2 -> [City 0, City 1, City 3]
City 3 -> [City 1, City 2]
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.

Example 2:

find the city 02
Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
Output: 0
Explanation: The figure above describes the graph.
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -> [City 1]
City 1 -> [City 0, City 4]
City 2 -> [City 3, City 4]
City 3 -> [City 2, City 4]
City 4 -> [City 1, City 2, City 3]
The city 0 has 1 neighboring city at a distanceThreshold = 2.

Constraints:

  • 2 ⇐ n ⇐ 100

  • 1 ⇐ edges.length ⇐ n * (n - 1) / 2

  • edges[i].length == 3

  • 0 ⇐ fromi < toi < n

  • 1 ⇐ weighti, distanceThreshold ⇐ 10^4

  • All pairs (fromi, toi) are distinct.

1
Unresolved directive in 1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1334_FindTheCityWithTheSmallestNumberOfNeighborsAtAThresholdDistance.java[]

1335. Minimum Difficulty of a Job Schedule

You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the i-th job, you have to finish all the jobs j where 0 ⇐ j < i).

You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done in that day.

Given an array of integers jobDifficulty and an integer d. The difficulty of the i-th job is jobDifficulty[i].

Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.

Example 1:

untitled
Input: jobDifficulty = [6,5,4,3,2,1], d = 2
Output: 7
Explanation: First day you can finish the first 5 jobs, total difficulty = 6.
Second day you can finish the last job, total difficulty = 1.
The difficulty of the schedule = 6 + 1 = 7

Example 2:

Input: jobDifficulty = [9,9,9], d = 4
Output: -1
Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.

Example 3:

Input: jobDifficulty = [1,1,1], d = 3
Output: 3
Explanation: The schedule is one job per day. total difficulty will be 3.

Example 4:

Input: jobDifficulty = [7,1,7,1,7,1], d = 3
Output: 15

Example 5:

Input: jobDifficulty = [11,111,22,222,33,333,44,444], d = 6
Output: 843

Constraints:

  • 1 ⇐ jobDifficulty.length ⇐ 300

  • 0 ⇐ jobDifficulty[i] ⇐ 1000

  • 1 ⇐ d ⇐ 10

1
Unresolved directive in 1335-minimum-difficulty-of-a-job-schedule.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1335_MinimumDifficultyOfAJobSchedule.java[]

1336. Number of Transactions per Visit

1
Unresolved directive in 1336-number-of-transactions-per-visit.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1336_NumberOfTransactionsPerVisit.java[]

1337. The K Weakest Rows in a Matrix

Given a m * n matrix mat of ones (representing soldiers) and zeros (representing civilians), return the indexes of the k weakest rows in the matrix ordered from the weakest to the strongest.

A row *i* is weaker than row *j*, if the number of soldiers in row *i* is less than the number of soldiers in row *j*, or they have the same number of soldiers but *i* is less than *j*. Soldiers are always stand in the frontier of a row, that is, always ones may appear first and then zeros.

Example 1:

Input: mat =
[[1,1,0,0,0],
 [1,1,1,1,0],
 [1,0,0,0,0],
 [1,1,0,0,0],
 [1,1,1,1,1]],
k = 3
Output: [2,0,3]
Explanation:
The number of soldiers for each row is:
row 0 -> 2
row 1 -> 4
row 2 -> 1
row 3 -> 2
row 4 -> 5
Rows ordered from the weakest to the strongest are [2,0,3,1,4]

Example 2:

Input: mat =
[[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [1,0,0,0]],
k = 2
Output: [0,2]
Explanation:
The number of soldiers for each row is:
row 0 -> 1
row 1 -> 4
row 2 -> 1
row 3 -> 1
Rows ordered from the weakest to the strongest are [0,2,3,1]

Constraints:

  • m == mat.length

  • n == mat[i].length

  • <font face="monospace">2 ⇐ n, m ⇐ 100

  • 1 ⇐ k ⇐ m

  • matrix[i][j] is either 0 or 1.

1
Unresolved directive in 1337-the-k-weakest-rows-in-a-matrix.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1337_TheKWeakestRowsInAMatrix.java[]

1338. Reduce Array Size to The Half

Given an array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.

Return the minimum size of the set so that at least half of the integers of the array are removed.

Example 1:

Input: arr = [3,3,3,3,5,5,5,2,2,7]
Output: 2
Explanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has size greater than half of the size of the old array.

Example 2:

Input: arr = [7,7,7,7,7,7]
Output: 1
Explanation: The only possible set you can choose is {7}. This will make the new array empty.

Example 3:

Input: arr = [1,9]
Output: 1

Example 4:

Input: arr = [1000,1000,3,7]
Output: 1

Example 5:

Input: arr = [1,2,3,4,5,6,7,8,9,10]
Output: 5

Constraints:

  • 1 ⇐ arr.length ⇐ 10^5

  • arr.length is even.

  • 1 ⇐ arr[i] ⇐ 10^5

1
Unresolved directive in 1338-reduce-array-size-to-the-half.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1338_ReduceArraySizeToTheHalf.java[]

1339. Maximum Product of Splitted Binary Tree

Given a binary tree root. Split the binary tree into two subtrees by removing 1 edge such that the product of the sums of the subtrees are maximized.

Since the answer may be too large, return it modulo 10^9 + 7.

Example 1:

sample 1 1699
Input: root = [1,2,3,4,5,6]
Output: 110
Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)

Example 2:

sample 2 1699
Input: root = [1,null,2,3,4,null,null,5,6]
Output: 90
Explanation:  Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)

Example 3:

Input: root = [2,3,9,10,7,8,6,5,4,11,1]
Output: 1025

Example 4:

Input: root = [1,1]
Output: 1

Constraints:

  • Each tree has at most 50000 nodes and at least 2 nodes.

  • Each node’s value is between [1, 10000].

1
Unresolved directive in 1339-maximum-product-of-splitted-binary-tree.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1339_MaximumProductOfSplittedBinaryTree.java[]

1340. Jump Game V

Given an array of integers arr and an integer d. In one step you can jump from index i to index:

  • i + x where: i + x < arr.length and ` 0 < x ⇐ d`.

  • i - x where: i - x >= 0 and ` 0 < x ⇐ d`.

In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).

You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.

Notice that you can not jump outside of the array at any time.

Example 1:

meta chart
Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2
Output: 4
Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.

Example 2:

Input: arr = [3,3,3,3,3], d = 3
Output: 1
Explanation: You can start at any index. You always cannot jump to any index.

Example 3:

Input: arr = [7,6,5,4,3,2,1], d = 1
Output: 7
Explanation: Start at index 0. You can visit all the indicies.

Example 4:

Input: arr = [7,1,7,1,7,1], d = 2
Output: 2

Example 5:

Input: arr = [66], d = 1
Output: 1

Constraints:

  • 1 ⇐ arr.length ⇐ 1000

  • 1 ⇐ arr[i] ⇐ 10^5

  • 1 ⇐ d ⇐ arr.length

1
Unresolved directive in 1340-jump-game-v.adoc - include::/home/runner/work/leetcode/leetcode/src/main/java/com/diguage/algorithm/leetcode/_1340_JumpGameV.java[]