From d96227e939952056ddbce16bbcd16c1eed76dc82 Mon Sep 17 00:00:00 2001
From: Shuo We have two special characters. The first character can be represented by one bit We have two special characters: 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. Given a binary array Example 1: Example 1:0
. The second character can be represented by two bits (10
or 11
).
+
+
+0
.10
or 11
).bits
that ends with 0
, return true
if the last character must be a one-bit character.
-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.
+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:
+
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. +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
.bits[i]
is always 0
or 1
.+
Constraints:
+ +1 <= bits.length <= 1000
bits[i]
is either 0
or 1
.Return true
if there is a 132 pattern in nums
, otherwise, return false
.
Follow up: The O(n^2)
is trivial, could you come up with the O(n logn)
or the O(n)
solution?
Example 1:
@@ -47,7 +45,7 @@n == nums.length
1 <= n <= 104
1 <= n <= 2 * 105
-109 <= nums[i] <= 109
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.
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.
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".
+"(1, 3)"
becomes s = "(13)"
and "(2, 0.5)"
becomes s = "(205)"
.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 fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring 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.)
+The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
+ ++
Example 1:
-Example 1: Input: s = "(123)" -Output: ["(1, 23)", "(12, 3)", "(1.2, 3)", "(1, 2.3)"] +Output: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]+
Example 2:
+-Example 2: -Input: s = "(00011)" -Output: ["(0.001, 1)", "(0, 0.011)"] -Explanation: -0.0, 00, 0001 or 00.01 are not allowed. +Input: s = "(0123)" +Output: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"] +Explanation: 0.0, 00, 0001 or 00.01 are not allowed.+
Example 3:
+-Example 3: -Input: s = "(0123)" -Output: ["(0, 123)", "(0, 12.3)", "(0, 1.23)", "(0.1, 23)", "(0.1, 2.3)", "(0.12, 3)"] +Input: s = "(00011)" +Output: ["(0, 0.011)","(0.001, 1)"]+
Example 4:
+-Example 4: Input: s = "(100)" -Output: [(10, 0)] -Explanation: -1.0 is not allowed. +Output: ["(10, 0)"] +Explanation: 1.0 is not allowed.
- -
Note:
+Constraints:
4 <= s.length <= 12
.s[0]
= "(", s[s.length - 1]
= ")", and the other elements in s
are digits.4 <= s.length <= 12
s[0] == '('
and s[s.length - 1] == ')'
.s
are digits.- ### Related Topics [[String](../../tag/string/README.md)] diff --git a/problems/array-nesting/README.md b/problems/array-nesting/README.md index 013bd69e1..938bd27cb 100644 --- a/problems/array-nesting/README.md +++ b/problems/array-nesting/README.md @@ -13,7 +13,7 @@
You are given an integer array nums
of length n
where nums
is a permutation of the numbers in the range [0, n - 1]
.
You should build a set s[k] = {nums[k], nums[nums[i]], nums[nums[nums[k]]], ... }
subjected to the following rule:
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }
subjected to the following rule:
s[k]
starts with the selection of the element nums[k]
of index = k
.Constraints:
2 <= asteroids.length <= 104
2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
Given a string s
representing an expression, implement a basic calculator to evaluate it.
Given a string s
representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Example 1:
@@ -37,6 +37,14 @@ Output: 23 +Example 4:
+ ++Input: s = "+48 + -48" +Output: 0 +Explanation: Numbers can have multiple digits and start with +/-. ++
Constraints:
@@ -44,6 +52,7 @@1 <= s.length <= 3 * 105
s
consists of digits, '+'
, '-'
, '('
, ')'
, and ' '
.s
represents a valid expression.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.)
Given an array nums
of 0
s and 1
s, consider xi
: the i-th subarray from nums[0]
to nums[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.
Return a list of booleans answer
, where answer[i]
is true
if and only if xi
is divisible by 5.
Example 1:
-Input: [0,1,1] +Input: nums = [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. @@ -27,21 +27,21 @@ The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. OExample 2:
-Input: [1,1,1] +Input: nums = [1,1,1] Output: [false,false,false]Example 3:
-Input: [0,1,1,1,1,1] +Input: nums = [0,1,1,1,1,1] Output: [true,false,false,false,true,false]Example 4:
-Input: [1,1,1,0,1] +Input: nums = [1,1,1,0,1] Output: [false,false,false,false,false]@@ -50,8 +50,8 @@ The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. ONote:
-
### Related Topics diff --git a/problems/binary-search/README.md b/problems/binary-search/README.md index 01078452d..86af03434 100644 --- a/problems/binary-search/README.md +++ b/problems/binary-search/README.md @@ -13,6 +13,8 @@- -
1 <= A.length <= 30000
- +
A[i]
is0
or1
- +
1 <= nums.length <= 30000
nums[i]
is0
or1
Given an array of integers
+nums
which is sorted in ascending order, and an integertarget
, write a function to searchtarget
innums
. Iftarget
exists, then return its index. Otherwise, return-1
.You must write an algorithm with
+O(log n)
runtime complexity.
Example 1:
diff --git a/problems/binary-string-with-substrings-representing-1-to-n/README.md b/problems/binary-string-with-substrings-representing-1-to-n/README.md index ee354f5bf..9d41ab3c5 100644 --- a/problems/binary-string-with-substrings-representing-1-to-n/README.md +++ b/problems/binary-string-with-substrings-representing-1-to-n/README.md @@ -11,21 +11,21 @@ ## [1016. Binary String With Substrings Representing 1 To N (Medium)](https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n "子串能表示从 1 到 N 数字的二进制串") -Given a binary string
+S
(a string consisting only of '0' and '1's) and a positive integerN
, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.Given a binary string
s
(a string consisting only of '0' and '1's) and a positive integern
, return true if and only if for every integerx
from1
ton
, the binary representation ofx
is a substring ofs
.
Example 1:
-Input: S = "0110", N = 3 +Input: s = "0110", n = 3 Output: trueExample 2:
-Input: S = "0110", N = 4 +Input: s = "0110", n = 4 Output: false@@ -34,8 +34,8 @@Note:
-
### Related Topics diff --git a/problems/binary-subarrays-with-sum/README.md b/problems/binary-subarrays-with-sum/README.md index 50524cd97..cc30e8af5 100644 --- a/problems/binary-subarrays-with-sum/README.md +++ b/problems/binary-subarrays-with-sum/README.md @@ -11,32 +11,38 @@ ## [930. Binary Subarrays With Sum (Medium)](https://leetcode.com/problems/binary-subarrays-with-sum "和相同的二元子数组") -- -
1 <= S.length <= 1000
- +
1 <= N <= 10^9
- +
1 <= s.length <= 1000
1 <= n <= 109
In an array
+nums
of0
s and1
s, how many non-empty subarrays have sumgoal
?Given a binary array
-nums
and an integergoal
, return the number of non-empty subarrays with a sumgoal
.+
A subarray is a contiguous part of the array.
+
Example 1:
-Input: nums = [1,0,1,0,1], goal = 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] +Input: nums = [1,0,1,0,1], goal = 2 +Output: 4 +Explanation: The 4 subarrays are bolded and underlined below: +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1] +[1,0,1,0,1]-+
Example 2:
-Note:
++Input: nums = [0,0,0,0,0], goal = 0 +Output: 15 ++ ++
Constraints:
--
+ ### Related Topics [[Hash Table](../../tag/hash-table/README.md)] diff --git a/problems/binary-tree-cameras/README.md b/problems/binary-tree-cameras/README.md index dc265c0a0..bebbe1d3e 100644 --- a/problems/binary-tree-cameras/README.md +++ b/problems/binary-tree-cameras/README.md @@ -11,41 +11,34 @@ ## [968. Binary Tree Cameras (Hard)](https://leetcode.com/problems/binary-tree-cameras "监控二叉树") -- +
nums.length <= 30000
+
- +
1 <= nums.length <= 3 * 104
nums[i]
is either0
or1
.- -
0 <= goal <= nums.length
- -
nums[i]
is either0
or1
.Given a binary tree, we install cameras on the nodes of the tree.
+You are given the
-root
of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.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.
+Return the minimum number of cameras needed to monitor all nodes of the tree.
-
Example 1:
-
+-Input: [0,0,null,0,0] -Output: 1 -Explanation: One camera is enough to monitor all nodes if placed as shown. +Input: root = [0,0,null,0,0] +Output: 1 +Explanation: One camera is enough to monitor all nodes if placed as shown.--Example 2:
-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. +Input: root = [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:+
Constraints:
--
-- The number of nodes in the given tree will be in the range
-[1, 1000]
.- Every node has value 0.
-
[1, 1000]
.Node.val == 0
2-3
](../binary-tree-postorder-traversal "Binary Tree Postorder Traversal")
-## [144. Binary Tree Preorder Traversal (Medium)](https://leetcode.com/problems/binary-tree-preorder-traversal "二叉树的前序遍历")
+## [144. Binary Tree Preorder Traversal (Easy)](https://leetcode.com/problems/binary-tree-preorder-traversal "二叉树的前序遍历")
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
We are given the head node root
of a binary tree, where additionally every node's value is either a 0 or a 1.
Given the root
of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1
has been removed.
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.)
+A subtree of a node node
is node
plus every node that is a descendant of node
.
+
Example 1:
+-Example 1: -Input: [1,null,0,0,1] -Output: [1,null,0,null,1] - +Input: root = [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. - -+![]()
Example 2:
+-Example 2: -Input: [1,0,1,0,0,0,1] -Output: [1,null,1,null,1] - - -++Input: root = [1,0,1,0,0,0,1] +Output: [1,null,1,null,1]
Example 3:
+-Example 3: -Input: [1,1,0,1,1,0,1,0] -Output: [1,1,0,1,1,null,1] - - --+Input: root = [1,1,0,1,1,0,1,0] +Output: [1,1,0,1,1,null,1]
Note:
++
Constraints:
200 nodes
.0
or 1
.[1, 200]
.Node.val
is either 0
or 1
.
Given a set of keywords words
and a string S
, make all appearances of all keywords in S
bold. Any letters between <b>
and </b>
tags become bold.
diff --git a/problems/buddy-strings/README.md b/problems/buddy-strings/README.md
index 3980f40a5..91ee10f90 100644
--- a/problems/buddy-strings/README.md
+++ b/problems/buddy-strings/README.md
@@ -11,9 +11,9 @@
## [859. Buddy Strings (Easy)](https://leetcode.com/problems/buddy-strings "亲密字符串")
-
Given two strings a
and b
, return true
if you can swap two letters in a
so the result is equal to b
, otherwise, return false
.
Given two strings s
and goal
, return true
if you can swap two letters in s
so the result is equal to goal
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at a[i]
and a[j]
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at s[i]
and s[j]
.
0
and 2
in "abcd"
results in "cbad"
.Example 1:
-Input: a = "ab", b = "ba" +Input: s = "ab", goal = "ba" Output: true -Explanation: You can swap a[0] = 'a' and a[1] = 'b' to get "ba", which is equal to b. +Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
Example 2:
-Input: a = "ab", b = "ab" +Input: s = "ab", goal = "ab" Output: false -Explanation: The only letters you can swap are a[0] = 'a' and a[1] = 'b', which results in "ba" != b. +Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
Example 3:
-Input: a = "aa", b = "aa" +Input: s = "aa", goal = "aa" Output: true -Explanation: You can swap a[0] = 'a' and a[1] = 'a' to get "aa", which is equal to b. +Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.
Example 4:
-Input: a = "aaaaaaabc", b = "aaaaaaacb" +Input: s = "aaaaaaabc", goal = "aaaaaaacb" Output: true@@ -55,8 +55,8 @@
Constraints:
1 <= a.length, b.length <= 2 * 104
a
and b
consist of lowercase letters.1 <= s.length, goal.length <= 2 * 104
s
and goal
consist of lowercase letters.A conveyor belt has packages that must be shipped from one port to another within D
days.
A conveyor belt has packages that must be shipped from one port to another within days
days.
The ith
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.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days
days.
Example 1:
-Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5 +Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 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 @@ -36,7 +36,7 @@ Note that the cargo must be shipped in the order given, so using a ship of capacExample 2:
-Input: weights = [3,2,2,4,1,4], D = 3 +Input: weights = [3,2,2,4,1,4], days = 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 @@ -47,7 +47,7 @@ Note that the cargo must be shipped in the order given, so using a ship of capacExample 3:
-Input: weights = [1,2,3,1,1], D = 4 +Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 @@ -60,7 +60,7 @@ Note that the cargo must be shipped in the order given, so using a ship of capacConstraints:
1 <= D <= weights.length <= 5 * 104
1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0
, 'b' -> 1
, 'c' -> 2
, etc.).
The numerical value of some string of lowercase English letters s
is the concatenation of the letter values of each letter in s
, which is then converted into an integer.
s = "acb"
, we concatenate each letter's letter value, resulting in "021"
. After converting it, we get 21
.You are given three strings firstWord
, secondWord
, and targetWord
, each consisting of lowercase English letters 'a'
through 'j'
inclusive.
Return true
if the summation of the numerical values of firstWord
and secondWord
equals the numerical value of targetWord
, or false
otherwise.
+
Example 1:
+ ++Input: firstWord = "acb", secondWord = "cba", targetWord = "cdb" +Output: true +Explanation: +The numerical value of firstWord is "acb" -> "021" -> 21. +The numerical value of secondWord is "cba" -> "210" -> 210. +The numerical value of targetWord is "cdb" -> "231" -> 231. +We return true because 21 + 210 == 231. ++ +
Example 2:
+ ++Input: firstWord = "aaa", secondWord = "a", targetWord = "aab" +Output: false +Explanation: +The numerical value of firstWord is "aaa" -> "000" -> 0. +The numerical value of secondWord is "a" -> "0" -> 0. +The numerical value of targetWord is "aab" -> "001" -> 1. +We return false because 0 + 0 != 1. ++ +
Example 3:
+ ++Input: firstWord = "aaa", secondWord = "a", targetWord = "aaaa" +Output: true +Explanation: +The numerical value of firstWord is "aaa" -> "000" -> 0. +The numerical value of secondWord is "a" -> "0" -> 0. +The numerical value of targetWord is "aaaa" -> "0000" -> 0. +We return true because 0 + 0 == 0. ++ +
+
Constraints:
+ +1 <= firstWord.length,
secondWord.length,
targetWord.length <= 8
firstWord
, secondWord
, and targetWord
consist of lowercase English letters from 'a'
to 'j'
inclusive.Additionally, the division that we use is floor division such that 10 * 9 / 8
equals 11
. This guarantees the result is an integer.
Implement the clumsy
function as defined above: given an integer N
, it returns the clumsy factorial of N
.
Implement the clumsy
function as defined above: given an integer n
, it returns the clumsy factorial of n
.
Example 1:
-Input: 4 +Input: n = 4 Output: 7 Explanation: 7 = 4 * 3 / 2 + 1@@ -34,7 +34,7 @@
Example 2:
-Input: 10
+Input: n = 10
Output: 12
Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
@@ -44,8 +44,8 @@
Note:
1 <= N <= 10000
-2^31 <= answer <= 2^31 - 1
(The answer is guaranteed to fit within a 32-bit integer.)1 <= n <= 10000
-231 <= answer <= 231 - 1
(The answer is guaranteed to fit within a 32-bit integer.)1 <= coins.length <= 300
1 <= coins[i] <= 5000
coins
are unique.0 <= amount <= 5000
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.
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.
For a given number n
in base-10, return the complement of it's binary representation as a base-10 integer.
@@ -26,7 +26,7 @@
Example 1:
-Input: 5 +Input: n = 5 Output: 2 Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.@@ -35,7 +35,7 @@
Example 2:
-Input: 7 +Input: n = 7 Output: 0 Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.@@ -44,7 +44,7 @@
Example 3:
-Input: 10 +Input: n = 10 Output: 5 Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.@@ -54,7 +54,7 @@
Note:
0 <= N < 10^9
0 <= n < 109
-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: +A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
+ +The world is modeled as an
-[[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]] +m x n
binary gridisInfected
, whereisInfected[i][j] == 0
represents uninfected cells, andisInfected[i][j] == 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 (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
+Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
+ ++
Example 1:
++
+Input: isInfected = [[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: +- -On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained. +
![]()
Example 2:
+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. +Input: isInfected = [[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:
+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. +Input: isInfected = [[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:
--
- + +- The number of rows and columns of
-grid
will each be in the range[1, 50]
.- Each
-grid[i][j]
will be either0
or1
.- Throughout the described process, there is always a contiguous viral region that will infect strictly more uncontaminated squares in the next round.
-+
Constraints:
+ +
m == isInfected.length
n == isInfected[i].length
1 <= m, n <= 50
isInfected[i][j]
is either 0
or 1
.Given a number N
, return a string consisting of "0"
s and "1"
s that represents its value in base -2
(negative two).
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 +Input: n = 2 Output: "110" Explantion: (-2) ^ 2 + (-2) ^ 1 = 2@@ -30,7 +30,7 @@
Example 2:
-Input: 3 +Input: n = 3 Output: "111" Explantion: (-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3@@ -39,7 +39,7 @@
Example 3:
-Input: 4 +Input: n = 4 Output: "100" Explantion: (-2) ^ 2 = 4@@ -49,7 +49,7 @@
Note:
0 <= N <= 10^9
0 <= n <= 109
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
diff --git a/problems/count-different-palindromic-subsequences/README.md b/problems/count-different-palindromic-subsequences/README.md index 1c3b901b2..ffc4a31e6 100644 --- a/problems/count-different-palindromic-subsequences/README.md +++ b/problems/count-different-palindromic-subsequences/README.md @@ -11,40 +11,38 @@ ## [730. Count Different Palindromic Subsequences (Hard)](https://leetcode.com/problems/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
.
Given a string s, return the number of different non-empty palindromic subsequences in s
. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence of a string s
is obtained by deleting 0 or more characters from s
.
A subsequence of a string is obtained by deleting zero or more characters from the string.
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
.
Two sequences a1, a2, ...
and b1, b2, ...
are different if there is some i
for which ai != bi
.
Example 1:
++
Example 1:
-Input: -s = 'bccb' -Output: 6 -Explanation: -The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. +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:
+Example 2:
-Input: -s = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' -Output: 104860361 -Explanation: -There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7. +Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba" +Output: 104860361 +Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.-
Note:
++
Constraints:
s
will be in the range [1, 1000]
.s[i]
will be in the set {'a', 'b', 'c', 'd'}
.1 <= s.length <= 1000
s[i]
is either 'a'
, 'b'
, 'c'
, or 'd'
.Constraints:
1 <= nums.length <= 104
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
-105 <= lower <= upper <= 105
Given an integer num
, return an array of the number of 1
's in the binary representation of every number in the range [0, num]
.
Given an integer n
, return an array ans
of length n + 1
such that for each i
(0 <= i <= n
), ans[i]
is the number of 1
's in the binary representation of i
.
Example 1:
-Input: num = 2 +Input: n = 2 Output: [0,1,1] Explanation: 0 --> 0 @@ -28,7 +28,7 @@Example 2:
-Input: num = 5 +Input: n = 5 Output: [0,1,1,2,1,2] Explanation: 0 --> 0 @@ -43,15 +43,14 @@Constraints:
0 <= num <= 105
0 <= n <= 105
Follow up:
O(32n)
. Can you do it in linear time O(n)
and possibly in a single pass?O(n)
space complexity?O(n log n)
. Can you do it in linear time O(n)
and possibly in a single pass?__builtin_popcount
in C++)?Given a list of daily temperatures temperatures
, 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 temperatures = [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]
.
Given an array of integers temperatures
represents the daily temperatures, return an array answer
such that answer[i]
is the number of days you have to wait after the ith
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
+
Example 1:
+Input: temperatures = [73,74,75,71,69,72,76,73] +Output: [1,1,4,2,1,1,0,0] +
Example 2:
+Input: temperatures = [30,40,50,60] +Output: [1,1,1,0] +
Example 3:
+Input: temperatures = [30,60,90] +Output: [1,1,0] ++
+
Constraints:
+ +1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
The Employee
table holds all employees. Every employee has an Id, and there is also a column for the department Id.
Table: Employee
++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| Id | int | +| Name | varchar | +| Salary | int | +| DepartmentId | int | ++--------------+---------+ +Id is the primary key for this table. +Each row contains the ID, name, salary, and department of one employee. ++ +
+ +
Table: Department
++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| Id | int | +| Name | varchar | ++-------------+---------+ +Id is the primary key for this table. +Each row contains the ID and the name of one department. ++ +
+ +
A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department.
+ +Write an SQL query to find the employees who are high earners in each of the departments.
+ +Return the result table in any order.
+ +The query result format is in the following example:
+ ++ +
+Employee table: +----+-------+--------+--------------+ | Id | Name | Salary | DepartmentId | +----+-------+--------+--------------+ @@ -25,34 +66,33 @@ | 6 | Randy | 85000 | 1 | | 7 | Will | 70000 | 1 | +----+-------+--------+--------------+ --
The Department
table holds all departments of the company.
-+----+----------+ -| Id | Name | -+----+----------+ -| 1 | IT | -| 2 | Sales | -+----+----------+ -+Department table: ++----+-------+ +| 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).
- -+Result table: +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | -| IT | Randy | 85000 | | IT | Joe | 85000 | +| IT | Randy | 85000 | | IT | Will | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+ --
Explanation:
+In the IT department: +- Max earns the highest unique salary +- Both Randy and Joe earn the second-highest unique salary +- Will earns the third-highest unique salary -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.
+In the Sales department: +- Henry earns the highest salary +- Sam earns the second-highest salary +- There is no third-highest salary as there are only two employees diff --git a/problems/design-hashmap/README.md b/problems/design-hashmap/README.md index d4234bdf2..249925e46 100644 --- a/problems/design-hashmap/README.md +++ b/problems/design-hashmap/README.md @@ -52,9 +52,6 @@ myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]104
calls will be made to put
, get
, and remove
.-
Follow up: Please do not use the built-in HashMap library.
- ### Related Topics [[Design](../../tag/design/README.md)] [[Hash Table](../../tag/hash-table/README.md)] diff --git a/problems/design-hashset/README.md b/problems/design-hashset/README.md index c073a3e73..33cc69073 100644 --- a/problems/design-hashset/README.md +++ b/problems/design-hashset/README.md @@ -50,9 +50,6 @@ myHashSet.contains(2); // return False, (already removed)104
calls will be made to add
, remove
, and contains
.-Follow up: Could you solve the problem without using the built-in HashSet library? - ### Related Topics [[Design](../../tag/design/README.md)] [[Hash Table](../../tag/hash-table/README.md)] diff --git a/problems/distribute-coins-in-binary-tree/README.md b/problems/distribute-coins-in-binary-tree/README.md index f58dc8a7c..6035b24d6 100644 --- a/problems/distribute-coins-in-binary-tree/README.md +++ b/problems/distribute-coins-in-binary-tree/README.md @@ -11,15 +11,15 @@ ## [979. Distribute Coins in Binary Tree (Medium)](https://leetcode.com/problems/distribute-coins-in-binary-tree "在二叉树中分配硬币") -
You are given the root
of a binary tree with n
nodes where each node
in the tree has node.val
coins and there are n
coins total.
You are given the root
of a binary tree with n
nodes where each node
in the tree has node.val
coins. There are n
coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. (A move may be from parent to child, or from child to parent.)
+In one move, we may choose two adjacent nodes and move one coin from one node to another. A 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.
+Return the minimum number of moves required to make every node have exactly one coin.
Example 1:
-Input: root = [3,0,0] Output: 2 @@ -27,22 +27,22 @@
Example 2:
-Input: root = [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. +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:
-Input: root = [1,0,2] Output: 2
Example 4:
-Input: root = [1,0,0,null,3] Output: 4 @@ -55,7 +55,7 @@
n
.1 <= n <= 100
0 <= Node.val <= n
Node.val
is n
.Node.val
is n
.You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.
+You have a data structure of employee information, which includes the employee's unique id, their importance value, and their 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.
+You are given an array of employees employees
where:
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 their subordinates.
+employees[i].id
is the ID of the ith
employee.employees[i].importance
is the importance value of the ith
employee.employees[i].subordinates
is a list of the IDs of the subordinates of the ith
employee.Example 1:
+Given an integer id
that represents the ID of an employee, return the total importance value of this employee and all their 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. +Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 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:
+Example 2:
++Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5 +Output: -3 +-
+
Constraints:
+ +1 <= employees.length <= 2000
1 <= employees[i].id <= 2000
employees[i].id
are unique.-100 <= employees[i].importance <= 100
id
is guaranteed to be a valid employee id.To some string s
, we will perform some replacement operations that replace groups of letters with new ones (not necessarily the same size).
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 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.
Each replacement operation has 3
parameters: a starting index i
, a source word x
and a target word y
. The rule is that if 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 2
in the original string s
, we will replace it with "ffff"
.
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 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'
.
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.
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:
@@ -53,7 +53,7 @@sources.length == indexes.length
targets.length == indexes.length
1 <= sources[i].length, targets[i].length <= 50
sources[i]
and targets[i]
consist of only lowercase English letters.sources[i]
and targets[i]
consist of only lowercase English letters.You have a list of words
and a pattern
, and you want to know which words in words
matches the pattern.
Given a list of strings words
and a string pattern
, return a list of words[i]
that match pattern
. You may return the answer in any order.
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.
+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.
- -
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.+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. + -
+
Example 2:
-Note:
++Input: words = ["a","b","c"], pattern = "a" +Output: ["a","b","c"] ++ +
+
Constraints:
1 <= pattern.length <= 20
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
words[i].length == pattern.length
pattern
and words[i]
are lowercase English letters.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.
Given an array words
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.
@@ -38,9 +38,9 @@Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j]
is a lowercase letter1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.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.
+The distance of a pair of integers a
and b
is defined as the absolute difference between a
and b
.
Given an integer array nums
and an integer k
, return the kth
smallest distance among all the pairs nums[i]
and nums[j]
where 0 <= i < j < nums.length
.
+
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. ++ +
Example 2:
-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. +Input: nums = [1,1,1], k = 2 +Output: 0- - -
Note:
-
2 <= len(nums) <= 10000
.0 <= nums[i] < 1000000
.1 <= k <= len(nums) * (len(nums) - 1) / 2
.Example 3:
+ ++Input: nums = [1,6,1], k = 3 +Output: 5 ++ +
+
Constraints:
+ +n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
Given the sorted rotated array nums
that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
+
Example 1:
Input: nums = [1,3,5] @@ -41,7 +43,9 @@-Follow up: This is the same as Find Minimum in Rotated Sorted Array but with duplicates. Would allow duplicates affect the run-time complexity? How and why? +
Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but
+ +nums
may contain duplicates. Would this affect the runtime complexity? How and why?### Related Topics [[Array](../../tag/array/README.md)] diff --git a/problems/find-smallest-letter-greater-than-target/README.md b/problems/find-smallest-letter-greater-than-target/README.md index c308f8ce4..590b9cc02 100644 --- a/problems/find-smallest-letter-greater-than-target/README.md +++ b/problems/find-smallest-letter-greater-than-target/README.md @@ -11,53 +11,60 @@ ## [744. Find Smallest Letter Greater Than Target (Easy)](https://leetcode.com/problems/find-smallest-letter-greater-than-target "寻找比目标字母大的最小字母") -
-Given a list of sorted characters
letters
containing only lowercase letters, and given a target lettertarget
, 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'
andletters = ['a', 'b']
, the answer is'a'
. -Given a characters array
+ +letters
that is sorted in non-decreasing order and a charactertarget
, return the smallest character in the array that is larger thantarget
.Note that the letters wrap around.
+ +
target == 'z'
and letters == ['a', 'b']
, the answer is 'a'
.+
Example 1:
+ ++Input: letters = ["c","f","j"], target = "a" +Output: "c" ++ +
Example 2:
+ ++Input: letters = ["c","f","j"], target = "c" +Output: "f" ++ +
Example 3:
-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" +Input: letters = ["c","f","j"], target = "d" +Output: "f"- - -
Note:
-
letters
has a length in range [2, 10000]
.letters
consists of lowercase letters, and contains at least 2 unique letters.target
is a lowercase letter.Example 4:
+ ++Input: letters = ["c","f","j"], target = "g" +Output: "j" ++ +
Example 5:
+ ++Input: letters = ["c","f","j"], target = "j" +Output: "c" ++ +
+
Constraints:
+ +2 <= letters.length <= 104
letters[i]
is a lowercase English letter.letters
is sorted in non-decreasing order.letters
contains at least two different characters.target
is a lowercase English letter.There is only one repeated number in nums
, return this repeated number.
You must solve the problem without modifying the array nums
and uses only constant extra space.
Example 1:
Input: nums = [1,3,4,2,2] @@ -33,7 +35,7 @@Constraints:
2 <= n <= 105
1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums
appear only once except for precisely one integer which appears two or more times.nums
?nums
?O(1)
extra space?O(n2)
?You are given two integer arrays nums1
and nums2
. You are tasked to implement a data structure that supports queries of two types:
nums2
.(i, j)
such that nums1[i] + nums2[j]
equals a given value (0 <= i < nums1.length
and 0 <= j < nums2.length
).Implement the FindSumPairs
class:
FindSumPairs(int[] nums1, int[] nums2)
Initializes the FindSumPairs
object with two integer arrays nums1
and nums2
.void add(int index, int val)
Adds val
to nums2[index]
, i.e., apply nums2[index] += val
.int count(int tot)
Returns the number of pairs (i, j)
such that nums1[i] + nums2[j] == tot
.+
Example 1:
+ ++Input +["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"] +[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]] +Output +[null, 8, null, 2, 1, null, null, 11] + +Explanation +FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]); +findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4 +findSumPairs.add(3, 2); // now nums2 = [1,4,5,4+ +,5,4
] +findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5 +findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1 +findSumPairs.add(0, 1); // now nums2 = [2
,4,5,4,5,4
] +findSumPairs.add(1, 1); // now nums2 = [2
,5,5,4,5,4
] +findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4 +
+
Constraints:
+ +1 <= nums1.length <= 1000
1 <= nums2.length <= 105
1 <= nums1[i] <= 109
1 <= nums2[i] <= 105
0 <= index < nums2.length
1 <= val <= 105
1 <= tot <= 109
1000
calls are made to add
and count
each.boolean hasNext()
Returns true
if there are still some integers in the nested list and false
otherwise.Your code will be tested with the following pseudocode:
+ ++initialize iterator with nestedList +res = [] +while iterator.hasNext() + append iterator.next() to the end of res +return res ++ +
If res
matches the expected flattened list, then your code will be judged as correct.
Example 1:
diff --git a/problems/flood-fill/README.md b/problems/flood-fill/README.md index 2b88dd868..cb7e45206 100644 --- a/problems/flood-fill/README.md +++ b/problems/flood-fill/README.md @@ -11,34 +11,42 @@ ## [733. Flood Fill (Easy)](https://leetcode.com/problems/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:
+
An image is represented by an m x n
integer grid image
where image[i][j]
represents the pixel value of the image.
You are also given three integers sr
, sc
, and newColor
. You should perform a flood fill on the image starting from the pixel image[sr][sc]
.
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), and so on. Replace the color of all of the aforementioned pixels with newColor
.
Return the modified image after performing the flood fill.
+ ++
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. +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) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) 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: -
image
and image[0]
will be in the range [1, 50]
.0 <= sr < image.length
and 0 <= sc < image[0].length
.image[i][j]
and newColor
will be an integer in [0, 65535]
.Example 2:
+ ++Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2 +Output: [[2,2,2],[2,2,2]] ++ +
+
Constraints:
+ +m == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], newColor < 216
0 <= sr <= m
0 <= sc <= n
You are given an m x n
integer matrix grid
.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid
. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
+ +Return the biggest three distinct rhombus sums in the grid
in descending order. If there are less than three distinct values, return all of them.
+
Example 1:
++Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]] +Output: [228,216,211] +Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above. +- Blue: 20 + 3 + 200 + 5 = 228 +- Red: 200 + 2 + 10 + 4 = 216 +- Green: 5 + 200 + 4 + 2 = 211 ++ +
Example 2:
++Input: grid = [[1,2,3],[4,5,6],[7,8,9]] +Output: [20,9,8] +Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above. +- Blue: 4 + 2 + 6 + 8 = 20 +- Red: 9 (area 0 rhombus in the bottom right corner) +- Green: 8 (area 0 rhombus in the bottom middle) ++ +
Example 3:
+ ++Input: grid = [[7,7,7]] +Output: [7] +Explanation: All three possible rhombus sums are the same, so return [7]. ++ +
+
Constraints:
+ +m == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 105
The gray code is a binary numeral system where two successive values differ in only one bit.
+An n-bit gray code sequence is a sequence of 2n
integers where:
Given an integer n
representing the total number of bits in the code, return any sequence of gray code.
[0, 2n - 1]
,0
,A gray code sequence must begin with 0
.
Given an integer n
, return any valid n-bit gray code sequence.
Example 1:
@@ -24,15 +30,16 @@ Input: n = 2 Output: [0,1,3,2] Explanation: -00 - 0 -01 - 1 -11 - 3 -10 - 2 -[0,2,3,1] is also a valid gray code sequence. -00 - 0 -10 - 2 -11 - 3 -01 - 1 +The binary representation of [0,1,3,2] is [00,01,11,10]. +- 00 and 01 differ by one bit +- 01 and 11 differ by one bit +- 11 and 10 differ by one bit +- 10 and 00 differ by one bit +[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01]. +- 00 and 10 differ by one bit +- 10 and 11 differ by one bit +- 11 and 01 differ by one bit +- 01 and 00 differ by one bitExample 2:
diff --git a/problems/grid-illumination/README.md b/problems/grid-illumination/README.md index fc997ff9a..56d12503b 100644 --- a/problems/grid-illumination/README.md +++ b/problems/grid-illumination/README.md @@ -11,7 +11,7 @@ ## [1001. Grid Illumination (Hard)](https://leetcode.com/problems/grid-illumination "网格照明") -There is a 2D grid
of size N x N
where each cell of this grid has a lamp that is initially turned off.
There is a 2D grid
of size n x n
where each cell of this grid has a lamp that is initially turned off.
You are given a 2D array of lamp positions lamps
, where lamps[i] = [rowi, coli]
indicates that the lamp at grid[rowi][coli]
is turned on. Even if the same lamp is listed more than once, it is turned on.
Example 1:
-Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] +Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]] Output: [1,0] Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4]. The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square. @@ -37,14 +37,14 @@ The 1st query asks if the lamp at grid[1][0] is illuminated or nExample 2:
-Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] +Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]] Output: [1,1]Example 3:
-Input: N = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] +Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]] Output: [1,1,0]@@ -52,13 +52,13 @@ The 1st query asks if the lamp at grid[1][0] is illuminated or nConstraints:
1 <= N <= 109
1 <= n <= 109
0 <= lamps.length <= 20000
0 <= queries.length <= 20000
lamps[i].length == 2
0 <= rowi, coli < N
0 <= rowi, coli < n
queries[j].length == 2
0 <= rowj, colj < N
0 <= rowj, colj < n
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.
The bookstore owner knows a secret technique to keep themselves not grumpy for minutes
minutes straight, but can only use it once.
Return the maximum number of customers that can be satisfied throughout the day.
@@ -24,7 +24,7 @@Example 1:
-Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3 +Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 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. @@ -35,7 +35,7 @@ The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 =Note:
1 <= X <= customers.length == grumpy.length <= 20000
1 <= minutes <= customers.length == grumpy.length <= 20000
0 <= customers[i] <= 1000
0 <= grumpy[i] <= 1
Constraints:
1 <= nums.length <= 105
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
You are given two integers memory1
and memory2
representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.
At the ith
second (starting from 1), i
bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i
bits of available memory, the program crashes.
Return an array containing [crashTime, memory1crash, memory2crash]
, where crashTime
is the time (in seconds) when the program crashed and memory1crash
and memory2crash
are the available bits of memory in the first and second sticks respectively.
+
Example 1:
+ ++Input: memory1 = 2, memory2 = 2 +Output: [3,1,0] +Explanation: The memory is allocated as follows: +- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory. +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory. +- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively. ++ +
Example 2:
+ ++Input: memory1 = 8, memory2 = 11 +Output: [6,0,4] +Explanation: The memory is allocated as follows: +- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory. +- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory. +- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory. +- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory. +- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory. +- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively. ++ +
+
Constraints:
+ +0 <= memory1, memory2 <= 231 - 1
Implement the RandomizedSet
class:
Given a start IP address ip
and a number of ips we need to cover n
, return a representation of the range as a list (of smallest possible length) of CIDR blocks.
diff --git a/problems/is-subsequence/README.md b/problems/is-subsequence/README.md
index 7675c6b1e..2069b926d 100644
--- a/problems/is-subsequence/README.md
+++ b/problems/is-subsequence/README.md
@@ -11,9 +11,9 @@
## [392. Is Subsequence (Easy)](https://leetcode.com/problems/is-subsequence "判断子序列")
-
Given two strings s
and t
, check if s
is a subsequence of t
.
Given two strings s
and t
, return true
if s
is a subsequence of t
, or false
otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
@@ -29,11 +29,11 @@0 <= s.length <= 100
0 <= t.length <= 104
s
and t
consist only of lowercase English letters.s
and t
consist only of lowercase English letters.-Follow up: If there are lots of incoming
s
, say s1, s2, ..., sk
where k >= 109
, and you want to check one by one to see if t
has its subsequence. In this scenario, how would you change your code?
+Follow up: Suppose there are lots of incoming s
, say s1, s2, ..., sk
where k >= 109
, and you want to check one by one to see if t
has its subsequence. In this scenario, how would you change your code?
### Related Topics
[[Greedy](../../tag/greedy/README.md)]
diff --git a/problems/jump-game-ii/README.md b/problems/jump-game-ii/README.md
index ac0e0385c..a6f6dffcd 100644
--- a/problems/jump-game-ii/README.md
+++ b/problems/jump-game-ii/README.md
@@ -39,8 +39,8 @@
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 105
1 <= nums.length <= 104
0 <= nums[i] <= 1000
You are given a 0-indexed binary string s
and two integers minJump
and maxJump
. In the beginning, you are standing at index 0
, which is equal to '0'
. You can move from index i
to index j
if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1)
, ands[j] == '0'
.Return true
if you can reach index s.length - 1
in s
, or false
otherwise.
+
Example 1:
+ ++Input: s = "011010", minJump = 2, maxJump = 3 +Output: true +Explanation: +In the first step, move from index 0 to index 3. +In the second step, move from index 3 to index 5. ++ +
Example 2:
+ ++Input: s = "01101110", minJump = 2, maxJump = 3 +Output: false ++ +
+
Constraints:
+ +2 <= s.length <= 105
s[i]
is either '0'
or '1'
.s[0] == '0'
1 <= minJump <= maxJump < s.length
Constraints:
1 <= nums.length <= 3 * 104
1 <= nums.length <= 104
0 <= nums[i] <= 105
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
.
We build a table of n
rows (1-indexed). We start by writing 0
in the 1st
row. 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 kth
indexed symbol in row n
. (The values of k
are 1-indexed.) (1 indexed).
n = 3
, the 1st
row is 0
, the 2nd
row is 01
, and the 3rd
row is 0110
.Given two integer n
and k
, return the kth
(1-indexed) symbol in the nth
row of a table of n
rows.
+
Example 1:
-Examples: Input: n = 1, k = 1 Output: 0 +Explanation: row 1: 0 ++ +
Example 2:
+Input: n = 2, k = 1 Output: 0 +Explanation: +row 1: 0 +row 2: 01 ++
Example 3:
+ +Input: n = 2, k = 2 Output: 1 +Explanation: +row 1: 0 +row 2: 01 +-Input: n = 4, k = 5 -Output: 1 +
Example 4:
++Input: n = 3, k = 1 +Output: 0 Explanation: row 1: 0 row 2: 01 -row 3: 0110 -row 4: 01101001 +row 3: 0110-
Note:
++
Constraints:
-n
will be an integer in the range [1, 30]
.k
will be an integer in the range [1, 2n-1]
.1 <= n <= 30
1 <= k <= 2n - 1
A sequence X1, X2, ..., Xn
is Fibonacci-like if:
A sequence x1, x2, ..., xn
is Fibonacci-like if:
n >= 3
Xi + Xi+1 = Xi+2
for all i + 2 <= n
xi + xi+1 == xi+2
for all i + 2 <= n
Given a strictly increasing array arr
of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr
. If one does not exist, return 0
.
Given a strictly increasing array arr
of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr
. If one does not exist, return 0
.
A subsequence is derived from another sequence arr
by deleting any number of elements (including none) from arr
, without changing the order of the remaining elements. For example, [3, 5, 8]
is a subsequence of [3, 4, 5, 6, 7, 8]
.
A subsequence is derived from another sequence arr
by deleting any number of elements (including none) from arr
, 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:
diff --git a/problems/lexicographical-numbers/README.md b/problems/lexicographical-numbers/README.md index 8d96fd73a..f8fabfcc2 100644 --- a/problems/lexicographical-numbers/README.md +++ b/problems/lexicographical-numbers/README.md @@ -13,6 +13,8 @@Given an integer n
, return all the numbers in the range [1, n]
sorted in lexicographical order.
You must write an algorithm that runs in O(n)
time and uses O(1)
extra space.
Example 1:
Input: n = 13 @@ -27,6 +29,3 @@
1 <= n <= 5 * 104
-
Follow up: Could you optimize your solution to use O(n)
runtime and O(1)
space?
Given a binary string s
, return true
if the longest contiguous segment of 1
s is strictly longer than the longest contiguous segment of 0
s in s
. Return false
otherwise.
s = "110100010"
the longest contiguous segment of 1
s has length 2
, and the longest contiguous segment of 0
s has length 3
.Note that if there are no 0
s, then the longest contiguous segment of 0
s is considered to have length 0
. The same applies if there are no 1
s.
+
Example 1:
+ ++Input: s = "1101" +Output: true +Explanation: +The longest contiguous segment of 1s has length 2: "1101" +The longest contiguous segment of 0s has length 1: "1101" +The segment of 1s is longer, so return true. ++ +
Example 2:
+ ++Input: s = "111000" +Output: false +Explanation: +The longest contiguous segment of 1s has length 3: "111000" +The longest contiguous segment of 0s has length 3: "111000" +The segment of 1s is not longer, so return false. ++ +
Example 3:
+ ++Input: s = "110100010" +Output: false +Explanation: +The longest contiguous segment of 1s has length 2: "110100010" +The longest contiguous segment of 0s has length 3: "110100010" +The segment of 1s is not longer, so return false. ++ +
+
Constraints:
+ +1 <= s.length <= 100
s[i]
is either '0'
or '1'
.Given an array A
of integers, return the length of the longest arithmetic subsequence in A
.
Given an array nums
of integers, return the length of the longest arithmetic subsequence in nums
.
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
).
Recall that a subsequence of an array nums
is a list nums[i1], nums[i2], ..., nums[ik]
with 0 <= i1 < i2 < ... < ik <= nums.length - 1
, and that a sequence seq
is arithmetic if seq[i+1] - seq[i]
are all the same value (for 0 <= i < seq.length - 1
).
Example 1:
-Input: A = [3,6,9,12] +Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. @@ -28,7 +28,7 @@ The whole array is an arithmetic sequence with steps of length = 3.Example 2:
-Input: A = [9,4,7,2,10] +Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. @@ -37,7 +37,7 @@ The longest arithmetic subsequence is [4,7,10].Example 3:
-Input: A = [20,1,15,3,10,5,8] +Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5]. @@ -47,8 +47,8 @@ The longest arithmetic subsequence is [20,15,10,5].Constraints:
2 <= A.length <= 1000
0 <= A[i] <= 500
2 <= nums.length <= 1000
0 <= nums[i] <= 500
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Example 1:
@@ -33,13 +35,10 @@Constraints:
0 <= nums.length <= 104
0 <= nums.length <= 105
-109 <= nums[i] <= 109
-Follow up: Could you implement the
O(n)
solution?
-
### Related Topics
[[Union Find](../../tag/union-find/README.md)]
[[Array](../../tag/array/README.md)]
diff --git a/problems/longest-increasing-subsequence/README.md b/problems/longest-increasing-subsequence/README.md
index 47fd7b3f7..f81399903 100644
--- a/problems/longest-increasing-subsequence/README.md
+++ b/problems/longest-increasing-subsequence/README.md
@@ -47,12 +47,7 @@
-
Follow up:
- -O(n2)
solution?O(n log(n))
time complexity?Follow up: Can you come up with an algorithm that runs in O(n log(n))
time complexity?
Given a list of words, each word consists of English lowercase letters.
+You are given an array of words
where each word consists of lowercase English 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"
.
wordA
is a predecessor of wordB
if and only if we can insert exactly one letter anywhere in wordA
without changing the order of the other characters to make it equal to wordB
.
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.
"abc"
is a predecessor of "abac"
, while "cba"
is not a predecessor of "bcad"
.Return the longest possible length of a word chain with words chosen from the given list of words
.
A word chain is a sequence of words [word1, word2, ..., wordk]
with k >= 1
, where word1
is a predecessor of word2
, word2
is a predecessor of word3
, and so on. A single word is trivially a word chain with k == 1
.
Return the length of the longest possible word chain with words chosen from the given list of words
.
Example 1:
@@ -25,7 +29,7 @@Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 -Explanation: One of the longest word chain is "a","ba","bda","bdca". +Explanation: One of the longest word chains is ["a","ba","bda","bdca"].
Example 2:
@@ -33,6 +37,16 @@Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 +Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. ++ +
Example 3:
+ ++Input: words = ["abcd","dbqca"] +Output: 1 +Explanation: The trivial word chain ["abcd"] is one of the longest word chains. +["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
@@ -41,7 +55,7 @@
1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i]
only consists of English lowercase letters.words[i]
only consists of lowercase English letters.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
.
We are given a matrix with rows
rows and cols
columns has cells with integer coordinates (r, c)
, where 0 <= r < rows
and 0 <= c < cols
.
Additionally, we are given a cell in that matrix with coordinates (r0, c0)
.
Additionally, we are given a cell in that matrix with coordinates (rCenter, cCenter)
.
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.)
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter)
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.)
@@ -23,18 +23,18 @@
Example 1:
-Input: R = 1, C = 2, r0 = 0, c0 = 0 +Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] -Explanation: The distances from (r0, c0) to other cells are: [0,1] +Explanation: The distances from (0, 0) to other cells are: [0,1]
Example 2:
-Input: R = 2, C = 2, r0 = 0, c0 = 1 +Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] -Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2] +Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.@@ -42,9 +42,9 @@ 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 +Input: rows = 2, cols = 3, rCenter = 1, cCenter = 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] +Explanation: The distances from (1, 2) 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]].@@ -53,10 +53,10 @@ There are other answers that would also be accepted as correct, such as [[1,2],[
Note:
1 <= R <= 100
1 <= C <= 100
0 <= r0 < R
0 <= c0 < C
1 <= rows <= 100
1 <= cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
Given an array points
containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi]
such that xi < xj
for all 1 <= i < j <= points.length
. You are also given an integer k
.
You are given an array points
containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi]
such that xi < xj
for all 1 <= i < j <= points.length
. You are also given an integer k
.
Find the maximum value of the equation yi + yj + |xi - xj|
where |xi - xj| <= k
and 1 <= i < j <= points.length
. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k
.
Return the maximum value of the equation yi + yj + |xi - xj|
where |xi - xj| <= k
and 1 <= i < j <= points.length
.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k
.
Example 1:
@@ -21,8 +23,9 @@Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1 Output: 4 -Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. -No other pairs satisfy the condition, so we return the max of 4 and 1.+Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1. +No other pairs satisfy the condition, so we return the max of 4 and 1. +
Example 2:
@@ -36,12 +39,12 @@ No other pairs satisfy the condition, so we return the max of 4 and 1.Constraints:
2 <= points.length <= 10^5
2 <= points.length <= 105
points[i].length == 2
-10^8 <= points[i][0], points[i][1] <= 10^8
0 <= k <= 2 * 10^8
points[i][0] < points[j][0]
for all 1 <= i < j <= points.length
xi
form a strictly increasing sequence.-108 <= xi, yi <= 108
0 <= k <= 2 * 108
xi < xj
for all 1 <= i < j <= points.length
xi
form a strictly increasing sequence.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.)
Given an array nums
of integers, we must modify the array in the following way: we choose an i
and replace nums[i]
with -nums[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.
@@ -20,27 +20,27 @@Example 1:
-Input: A = [4,2,3], K = 1 +Input: nums = [4,2,3], k = 1 Output: 5 -Explanation: Choose indices (1,) and A becomes [4,-2,3]. +Explanation: Choose indices (1,) and nums becomes [4,-2,3].
Example 2:
-Input: A = [3,-1,0,2], K = 3 +Input: nums = [3,-1,0,2], k = 3 Output: 6 -Explanation: Choose indices (1, 2, 2) and A becomes [3,1,0,2]. +Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
-Input: A = [2,-3,-1,5,-4], K = 2 +Input: nums = [2,-3,-1,5,-4], k = 2 Output: 13 -Explanation: Choose indices (1, 4) and A becomes [2,3,-1,5,4]. +Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Note:
1 <= A.length <= 10000
1 <= K <= 10000
-100 <= A[i] <= 100
1 <= nums.length <= 10000
1 <= k <= 10000
-100 <= nums[i] <= 100
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).
+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:
@@ -41,7 +41,7 @@1000
.[0, 104]
.[0, 104]
.Given an integer array nums
, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0
.
You must write an algorithm that runs in linear time and uses linear extra space.
+
Example 1:
@@ -38,8 +40,5 @@0 <= nums[i] <= 109
-Follow up: Could you solve it in linear time/space? - ### Related Topics [[Sort](../../tag/sort/README.md)] diff --git a/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/README.md b/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/README.md index ee1fefba8..ba8d02b14 100644 --- a/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/README.md +++ b/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/README.md @@ -9,7 +9,7 @@ [Next >](../minimum-cost-to-cut-a-stick "Minimum Cost to Cut a Stick") -## [1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target (Medium)](https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target "和为目标值的最大数目不重叠非空子数组数目") +## [1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target (Medium)](https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target "和为目标值且不重叠的非空子数组的最大数目")
Given an array nums
and an integer target
.
There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints
.
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints
.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k
cards.
Constraints:
1 <= cardPoints.length <= 10^5
1 <= cardPoints[i] <= 10^4
1 <= cardPoints.length <= 105
1 <= cardPoints[i] <= 104
1 <= k <= cardPoints.length
Given a circular array circ
of integers represented by nums
, find the maximum possible sum of a non-empty subarray of circ
.
Given a circular integer array nums
of length n
, return the maximum possible sum of a non-empty subarray of nums
.
Here, a circular array means the end of the array connects to the beginning of the array. (Formally, circ[i] = nums[i]
when 0 <= i < nums.length
, and circ[i+nums.length] = circ[i]
when i >= 0
.)
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i]
is nums[(i + 1) % n]
and the previous element of nums[i]
is nums[(i - 1 + n) % n]
.
Also, a subarray may only include each element of the fixed buffer nums
at most once. (Formally, for a subarray circ[i], circ[i+1], ..., circ[j]
, there does not exist i <= k1, k2 <= j
with k1 % nums.length = k2 % nums.length
.)
A subarray may only include each element of the fixed buffer nums
at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j]
, there does not exist i <= k1
, k2 <= j
with k1 % n == k2 % n
.
- -
Example 1:
-Input: nums = [1,-2,3,-2] -Output: 3 -Explanation: Subarray [3] has maximum sum 3 +Input: nums = [1,-2,3,-2] +Output: 3 +Explanation: Subarray [3] has maximum sum 3-
Example 2:
-Input: nums = [5,-3,5] -Output: 10 -Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10 +Input: nums = [5,-3,5] +Output: 10 +Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10-
Example 3:
-Input: nums = [3,-1,2,-1] -Output: 4 -Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4 +Input: nums = [3,-1,2,-1] +Output: 4 +Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4-
Example 4:
-Input: nums = [3,-2,2,-3] -Output: 3 -Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3 +Input: nums = [3,-2,2,-3] +Output: 3 +Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3
Example 5:
-Input: nums = [-2,-3,-1] -Output: -1 -Explanation: Subarray [-1] has maximum sum -1 +Input: nums = [-2,-3,-1] +Output: -1 +Explanation: Subarray [-1] has maximum sum -1
+
Constraints:
-Note:
- --30000 <= nums[i] <= 30000
1 <= nums.length <= 30000
n == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
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.)
Given an array nums
of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths firstLen
and secondLen
. (For clarification, the firstLen
-length subarray could occur before or after the secondLen
-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:
Formally, return the largest V
for which V = (nums[i] + nums[i+1] + ... + nums[i+firstLen-1]) + (nums[j] + nums[j+1] + ... + nums[j+secondLen-1])
and either:
0 <= i < i + L - 1 < j < j + M - 1 < A.length
, or0 <= j < j + M - 1 < i < i + L - 1 < A.length
.0 <= i < i + firstLen - 1 < j < j + secondLen - 1 < nums.length
, or0 <= j < j + secondLen - 1 < i < i + firstLen - 1 < nums.length
.@@ -29,7 +29,7 @@
Example 1:
-Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2 +Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 Output: 20 Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.@@ -38,7 +38,7 @@
Example 2:
-Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2 +Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 Output: 29 Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.@@ -47,7 +47,7 @@
Example 3:
-Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3 +Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 Output: 31 Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.@@ -57,10 +57,10 @@
Note:
L >= 1
M >= 1
L + M <= A.length <= 1000
0 <= A[i] <= 1000
firstLen >= 1
secondLen >= 1
firstLen + secondLen <= nums.length <= 1000
0 <= nums[i] <= 1000
You are given a very large integer n
, represented as a string, and an integer digit x
. The digits in n
and the digit x
are in the inclusive range [1, 9]
, and n
may represent a negative number.
You want to maximize n
's numerical value by inserting x
anywhere in the decimal representation of n
. You cannot insert x
to the left of the negative sign.
n = 73
and x = 6
, it would be best to insert it between 7
and 3
, making n = 763
.n = -55
and x = 2
, it would be best to insert it before the first 5
, making n = -255
.Return a string representing the maximum value of n
after the insertion.
+
Example 1:
+ ++Input: n = "99", x = 9 +Output: "999" +Explanation: The result is the same regardless of where you insert 9. ++ +
Example 2:
+ ++Input: n = "-13", x = 2 +Output: "-123" +Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123. ++ +
+
Constraints:
+ +1 <= n.length <= 105
1 <= x <= 9
n
are in the range [1, 9]
.n
is a valid representation of an integer.n
, it will begin with '-'
.Given an integer array nums
, return the maximum result of nums[i] XOR nums[j]
, where 0 ≤ i ≤ j < n
.
Follow up: Could you do this in O(n)
runtime?
Given an integer array nums
, return the maximum result of nums[i] XOR nums[j]
, where 0 <= i <= j < n
.
Example 1:
@@ -55,7 +53,7 @@Constraints:
1 <= nums.length <= 2 * 104
1 <= nums.length <= 2 * 105
0 <= nums[i] <= 231 - 1
Given two sorted integer arrays nums1
and nums2
, merge nums2
into nums1
as one sorted array.
You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
The number of elements initialized in nums1
and nums2
are m
and n
respectively. You may assume that nums1
has a size equal to m + n
such that it has enough space to hold additional elements from nums2
.
Merge nums1
and nums2
into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1
. To accommodate this, nums1
has a length of m + n
, where the first m
elements denote the elements that should be merged, and the last n
elements are set to 0
and should be ignored. nums2
has a length of n
.
Example 1:
-Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 + ++Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] -Example 2:
-Input: nums1 = [1], m = 1, nums2 = [], n = 0 +Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. +The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. ++ +Example 2:
+ ++Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] +Explanation: The arrays we are merging are [1] and []. +The result of the merge is [1].+ +Example 3:
+ ++Input: nums1 = [0], m = 0, nums2 = [1], n = 1 +Output: [1] +Explanation: The arrays we are merging are [] and [1]. +The result of the merge is [1]. +Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. ++
Constraints:
@@ -31,11 +54,11 @@
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[i] <= 109
-109 <= nums1[i], nums2[j] <= 109
-Follow up: Can you come up with an algorithm that runs in
O(m + n)
time?
+Follow up: Can you come up with an algorithm that runs in O(m + n)
time?
The pair sum of a pair (a,b)
is equal to a + b
. The maximum pair sum is the largest pair sum in a list of pairs.
(1,5)
, (2,3)
, and (4,4)
, the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.Given an array nums
of even length n
, pair up the elements of nums
into n / 2
pairs such that:
nums
is in exactly one pair, andReturn the minimized maximum pair sum after optimally pairing up the elements.
+ ++
Example 1:
+ ++Input: nums = [3,5,2,3] +Output: 7 +Explanation: The elements can be paired up into pairs (3,3) and (5,2). +The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. ++ +
Example 2:
+ ++Input: nums = [3,5,4,2,4,6] +Output: 8 +Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2). +The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. ++ +
+
Constraints:
+ +n == nums.length
2 <= n <= 105
n
is even.1 <= nums[i] <= 105
Given two strings s1, s2
, find the lowest ASCII sum of deleted characters to make two strings equal.
Given two strings s1
and s2
, return the lowest ASCII sum of deleted characters to make two strings equal.
+
Example 1:
-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. +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:
+
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. +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
.[97, 122]
.+
Constraints:
+ +1 <= s1.length, s2.length <= 1000
s1
and s2
consist of lowercase English letters.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
.
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days
. Each day is an integer from 1
to 365
.
Train tickets are sold in 3 different ways:
+Train tickets are sold in three different ways:
costs[0]
dollars;costs[1]
dollars;costs[2]
dollars.costs[0]
dollars,costs[1]
dollars, andcosts[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.
+The passes allow that many days of consecutive travel.
-Return the minimum number of dollars you need to travel every day in the given list of days
.
2
, then we can travel for 7
days: 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: +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. +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: +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. +In total, you spent $17 and covered all the days of your travel.
-
Constraints:
-Note:
- -1 <= days.length <= 365
1 <= days[i] <= 365
days
is in strictly increasing order.costs.length == 3
1 <= costs[i] <= 1000
There are N
piles of stones arranged in a row. The i
-th pile has stones[i]
stones.
There are n
piles of stones
arranged in a row. The ith
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.
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
.
Return 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]. +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. +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]. +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:
+Constraints:
1 <= stones.length <= 30
2 <= K <= 30
1 <= stones[i] <= 100
n == stones.length
1 <= n <= 30
1 <= stones[i] <= 100
2 <= k <= 30
In a row of dominoes, A[i]
and B[i]
represent the top and bottom halves of the ith
domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
In a row of dominoes, tops[i]
and bottoms[i]
represent the top and bottom halves of the ith
domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith
domino, so that A[i]
and B[i]
swap values.
We may rotate the ith
domino, so that tops[i]
and bottoms[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.
Return the minimum number of rotations so that all the values in tops
are the same, or all the values in bottoms
are the same.
If it cannot be done, return -1
.
Example 1:
--Input: A = [2,1,2,4,2,2], B = [5,2,6,2,3,2] +Input: tops = [2,1,2,4,2,2], bottoms = [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. +The first figure represents the dominoes as given by tops and bottoms: 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] +Input: tops = [3,5,1,2,3], bottoms = [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. @@ -43,8 +43,8 @@ In this case, it is not possible to rotate the dominoes to make one row of valueConstraints:
2 <= A.length == B.length <= 2 * 104
1 <= A[i], B[i] <= 6
2 <= tops.length == bottoms.length <= 2 * 104
1 <= tops[i], bottoms[i] <= 6
In one move, you can increment or decrement an element of the array by 1
.
Test cases are designed so that the answer will fit in a 32-bit integer.
+
Example 1:
diff --git a/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/README.md b/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/README.md new file mode 100644 index 000000000..3b23c6a24 --- /dev/null +++ b/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/README.md @@ -0,0 +1,65 @@ + + + + + + + +[< Previous](../sum-of-all-subset-xor-totals "Sum of All Subset XOR Totals") + +[Next >](../finding-pairs-with-a-certain-sum "Finding Pairs With a Certain Sum") + +## [1864. Minimum Number of Swaps to Make the Binary String Alternating (Medium)](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating "构成交替字符串需要的最小交换次数") + +Given a binary string s
, return the minimum number of character swaps to make it alternating, or -1
if it is impossible.
The string is called alternating if no two adjacent characters are equal. For example, the strings "010"
and "1010"
are alternating, while the string "0100"
is not.
Any two characters may be swapped, even if they are not adjacent.
+ ++
Example 1:
+ ++Input: s = "111000" +Output: 1 +Explanation: Swap positions 1 and 4: "111000" -> "101010" +The string is now alternating. ++ +
Example 2:
+ ++Input: s = "010" +Output: 0 +Explanation: The string is already alternating, no swaps are needed. ++ +
Example 3:
+ ++Input: s = "1110" +Output: -1 ++ +
+
Constraints:
+ +1 <= s.length <= 1000
s[i]
is either '0'
or '1'
.You are given an integer hoursBefore
, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n
roads. The road lengths are given as an integer array dist
of length n
, where dist[i]
describes the length of the ith
road in kilometers. In addition, you are given an integer speed
, which is the speed (in km/h) you will travel at.
After you travel road i
, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
1.4
hours, you must wait until the 2
hour mark before traveling the next road. If traveling a road takes exactly 2
hours, you do not need to wait.However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
+ +1.4
hours and traveling the second road takes 0.6
hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2
hour mark, letting you start traveling the third road immediately.Return the minimum number of skips required to arrive at the meeting on time, or -1
if it is impossible.
+
Example 1:
+ ++Input: dist = [1,3,2], speed = 4, hoursBefore = 2 +Output: 1 +Explanation: +Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours. +You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours. +Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest. ++ +
Example 2:
+ ++Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10 +Output: 2 +Explanation: +Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours. +You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours. ++ +
Example 3:
+ ++Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10 +Output: -1 +Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests. ++ +
+
Constraints:
+ +n == dist.length
1 <= n <= 1000
1 <= dist[i] <= 105
1 <= speed <= 106
1 <= hoursBefore <= 107
You are given a floating-point number hour
, representing the amount of time you have to reach the office. To commute to the office, you must take n
trains in sequential order. You are also given an integer array dist
of length n
, where dist[i]
describes the distance (in kilometers) of the ith
train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
+ +1st
train ride takes 1.5
hours, you must wait for an additional 0.5
hours before you can depart on the 2nd
train ride at the 2 hour mark.Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1
if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107
and hour
will have at most two digits after the decimal point.
+
Example 1:
+ ++Input: dist = [1,3,2], hour = 6 +Output: 1 +Explanation: At speed 1: +- The first train ride takes 1/1 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. +- You will arrive at exactly the 6 hour mark. ++ +
Example 2:
+ ++Input: dist = [1,3,2], hour = 2.7 +Output: 3 +Explanation: At speed 3: +- The first train ride takes 1/3 = 0.33333 hours. +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. +- You will arrive at the 2.66667 hour mark. ++ +
Example 3:
+ ++Input: dist = [1,3,2], hour = 1.9 +Output: -1 +Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. ++ +
+
Constraints:
+ +n == dist.length
1 <= n <= 105
1 <= dist[i] <= 105
1 <= hour <= 109
hour
.Given two strings s
and t
of lengths m
and n
respectively, return the minimum window in s
which will contain all the characters in t
. If there is no such window in s
that covers all characters in t
, return the empty string ""
.
Given two strings s
and t
of lengths m
and n
respectively, return the minimum window substring of s
such that every character in t
(including duplicates) is included in the window. If there is no such substring, return the empty string ""
.
Note that If there is such a window, it is guaranteed that there will always be only one unique minimum window in s
.
The testcases will be generated such that the answer is unique.
+ +A substring is a contiguous sequence of characters within the string.
Example 1:
-Input: s = "ADOBECODEBANC", t = "ABC" -Output: "BANC" -
Example 2:
-Input: s = "a", t = "a" -Output: "a" + ++Input: s = "ADOBECODEBANC", t = "ABC" +Output: "BANC" +Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. ++ +Example 2:
+ ++Input: s = "a", t = "a" +Output: "a" +Explanation: The entire string s is the minimum window. ++ +Example 3:
+ ++Input: s = "a", t = "aa" +Output: "" +Explanation: Both 'a's from t must be included in the window. +Since the largest window of s only has one 'a', return empty string.+
Constraints:
@@ -30,7 +50,7 @@
m == s.length
n == t.length
1 <= m, n <= 105
s
and t
consist of English letters.s
and t
consist of uppercase and lowercase English letters.diff --git a/problems/minimum-xor-sum-of-two-arrays/README.md b/problems/minimum-xor-sum-of-two-arrays/README.md new file mode 100644 index 000000000..a61323281 --- /dev/null +++ b/problems/minimum-xor-sum-of-two-arrays/README.md @@ -0,0 +1,67 @@ + + + + + + + +[< Previous](../get-biggest-three-rhombus-sums-in-a-grid "Get Biggest Three Rhombus Sums in a Grid") + +[Next >](../check-if-word-equals-summation-of-two-words "Check if Word Equals Summation of Two Words") + +## [1879. Minimum XOR Sum of Two Arrays (Hard)](https://leetcode.com/problems/minimum-xor-sum-of-two-arrays "两个数组最小的异或值之和") + +
You are given two integer arrays nums1
and nums2
of length n
.
The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])
(0-indexed).
[1,2,3]
and [3,2,1]
is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4
.Rearrange the elements of nums2
such that the resulting XOR sum is minimized.
Return the XOR sum after the rearrangement.
+ ++
Example 1:
+ ++Input: nums1 = [1,2], nums2 = [2,3] +Output: 2 +Explanation: Rearrange+ +nums2
so that it becomes[3,2]
. +The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
Example 2:
+ ++Input: nums1 = [1,0,3], nums2 = [5,3,4] +Output: 8 +Explanation: Rearrange+ +nums2
so that it becomes[5,4,3]
. +The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8. +
+
Constraints:
+ +n == nums1.length
n == nums2.length
1 <= n <= 14
0 <= nums1[i], nums2[i] <= 107
Given a non-negative integer n
, find the largest number that is less than or equal to n
with monotone increasing digits.
An integer has monotone increasing digits if and only if each pair of adjacent digits x
and y
satisfy x <= y
.
(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x
and y
satisfy x <= y
.)
Given an integer n
, return the largest number that is less than or equal to n
with monotone increasing digits.
Example 1:
++
Example 1:
-Input: n = 10 -Output: 9 +Input: n = 10 +Output: 9-
Example 2:
+Example 2:
-Input: n = 1234 -Output: 1234 +Input: n = 1234 +Output: 1234-
Example 3:
+Example 3:
-Input: n = 332 -Output: 299 +Input: n = 332 +Output: 299-
Note: n
is an integer in the range [0, 10^9]
.
+
Constraints:
+ +0 <= n <= 109
Given an n-ary tree, return the level order traversal of its nodes' values.
+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).
+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:
diff --git a/problems/n-ary-tree-preorder-traversal/README.md b/problems/n-ary-tree-preorder-traversal/README.md index ce13ab0d0..cfefd3582 100644 --- a/problems/n-ary-tree-preorder-traversal/README.md +++ b/problems/n-ary-tree-preorder-traversal/README.md @@ -50,6 +50,6 @@ [[Tree](../../tag/tree/README.md)] ### Similar Questions - 1. [Binary Tree Preorder Traversal](../binary-tree-preorder-traversal) (Medium) + 1. [Binary Tree Preorder Traversal](../binary-tree-preorder-traversal) (Easy) 1. [N-ary Tree Level Order Traversal](../n-ary-tree-level-order-traversal) (Medium) 1. [N-ary Tree Postorder Traversal](../n-ary-tree-postorder-traversal) (Easy) diff --git a/problems/n-queens/README.md b/problems/n-queens/README.md index f11283afb..d7813ecb5 100644 --- a/problems/n-queens/README.md +++ b/problems/n-queens/README.md @@ -13,7 +13,7 @@The n-queens puzzle is the problem of placing n
queens on an n x n
chessboard such that no two queens attack each other.
Given an integer n
, return all distinct solutions to the n-queens puzzle.
Given an integer n
, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space, respectively.
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.
+Table: Cinema
++----------------+----------+ +| Column Name | Type | ++----------------+----------+ +| id | int | +| movie | varchar | +| description | varchar | +| rating | float | ++----------------+----------+ +id is the primary key for this table. +Each row contains information about the name of a movie, its genre, and its rating. +rating is a 2 decimal places float in the range [0, 10] +
-
For example, table cinema
:
Write an SQL query to report the movies with an odd-numbered ID and a description that is not "boring"
.
-+---------+-----------+--------------+-----------+ -| 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: +
Return the result table in descending order by rating
.
-+---------+-----------+--------------+-----------+ -| id | movie | description | rating | -+---------+-----------+--------------+-----------+ -| 5 | House card| Interesting| 9.1 | -| 1 | War | great 3D | 8.9 | -+---------+-----------+--------------+-----------+ -+
The query result format is in the following example:
+ +
+Cinema table: ++----+------------+-------------+--------+ +| 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 | ++----+------------+-------------+--------+ + +Result table: ++----+------------+-------------+--------+ +| id | movie | description | rating | ++----+------------+-------------+--------+ +| 5 | House card | Interesting | 9.1 | +| 1 | War | great 3D | 8.9 | ++----+------------+-------------+--------+ + +We have three movies with odd-numbered ID: 1, 3, and 5. The movie with ID = 3 is boring so we don't include it in the answer.diff --git a/problems/number-of-1-bits/README.md b/problems/number-of-1-bits/README.md index c5a399386..dc25d62d8 100644 --- a/problems/number-of-1-bits/README.md +++ b/problems/number-of-1-bits/README.md @@ -61,7 +61,7 @@ ### Similar Questions 1. [Reverse Bits](../reverse-bits) (Easy) 1. [Power of Two](../power-of-two) (Easy) - 1. [Counting Bits](../counting-bits) (Medium) + 1. [Counting Bits](../counting-bits) (Easy) 1. [Binary Watch](../binary-watch) (Easy) 1. [Hamming Distance](../hamming-distance) (Easy) 1. [Binary Number with Alternating Bits](../binary-number-with-alternating-bits) (Easy) diff --git a/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/README.md b/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/README.md new file mode 100644 index 000000000..6bcd7d6c8 --- /dev/null +++ b/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/README.md @@ -0,0 +1,69 @@ + + + + + + + +[< Previous](../finding-pairs-with-a-certain-sum "Finding Pairs With a Certain Sum") + +[Next >](../orders-with-maximum-quantity-above-average "Orders With Maximum Quantity Above Average") + +## [1866. Number of Ways to Rearrange Sticks With K Sticks Visible (Hard)](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible "恰有 K 根木棍可以看到的排列数目") + +
There are n
uniquely-sized sticks whose lengths are integers from 1
to n
. You want to arrange the sticks such that exactly k
sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
[1,3,2,5,4]
, then the sticks with lengths 1
, 3
, and 5
are visible from the left.Given n
and k
, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7
.
+
Example 1:
+ ++Input: n = 3, k = 2 +Output: 3 +Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible. +The visible sticks are underlined. ++ +
Example 2:
+ ++Input: n = 5, k = 5 +Output: 1 +Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible. +The visible sticks are underlined. ++ +
Example 3:
+ ++Input: n = 20, k = 11 +Output: 647427950 +Explanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible. ++ +
+
Constraints:
+ +1 <= n <= 1000
1 <= k <= n
You have a pointer at index 0
in an array of size 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).
You have a pointer at index 0
in an array of size 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 steps
steps.
Since the answer may be too large, return it modulo 10^9 + 7
.
Given two integers steps
and arrLen
, return the number of ways such that your pointer still at index 0
after exactly steps
steps. Since the answer may be too large, return it modulo 109 + 7
.
Example 1:
@@ -52,7 +50,7 @@ Stay, Stay1 <= steps <= 500
1 <= arrLen <= 10^6
1 <= arrLen <= 106
Given a positive integer N
, return the number of positive integers less than or equal to N
that have at least 1 repeated digit.
Given a positive integer n
, return the number of positive integers less than or equal to n
that have at least 1 repeated digit.
@@ -19,7 +19,7 @@
Example 1:
-Input: 20 +Input: n = 20 Output: 1 Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.@@ -28,7 +28,7 @@
Example 2:
-Input: 100 +Input: n = 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.@@ -37,7 +37,7 @@
Example 3:
-Input: 1000 +Input: n = 1000 Output: 262@@ -47,7 +47,7 @@
Note:
1 <= N <= 10^9
1 <= n <= 109
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
.
Given two strings 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.
Return an array of all the words third
for each occurrence of "first second third"
.
-
Example 1:
- --Input: text = "alice is a good girl she is a good student", first = "a", second = "good" -Output: ["girl","student"] +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"]- --+ ### Related Topics [[Hash Table](../../tag/hash-table/README.md)] diff --git a/problems/orders-with-maximum-quantity-above-average/README.md b/problems/orders-with-maximum-quantity-above-average/README.md new file mode 100644 index 000000000..393ca3884 --- /dev/null +++ b/problems/orders-with-maximum-quantity-above-average/README.md @@ -0,0 +1,14 @@ + + + + + + + +[< Previous](../number-of-ways-to-rearrange-sticks-with-k-sticks-visible "Number of Ways to Rearrange Sticks With K Sticks Visible") + +[Next >](../product-of-two-run-length-encoded-arrays "Product of Two Run-Length Encoded Arrays") + +## [1867. Orders With Maximum Quantity Above Average (Medium)](https://leetcode.com/problems/orders-with-maximum-quantity-above-average "") + + diff --git a/problems/orders-with-maximum-quantity-above-average/mysql_schemas.sql b/problems/orders-with-maximum-quantity-above-average/mysql_schemas.sql new file mode 100644 index 000000000..1e84558f9 --- /dev/null +++ b/problems/orders-with-maximum-quantity-above-average/mysql_schemas.sql @@ -0,0 +1,16 @@ +Create table If Not Exists OrdersDetails (order_id int, product_id int, quantity int); +Truncate table OrdersDetails; +insert into OrdersDetails (order_id, product_id, quantity) values ('1', '1', '12'); +insert into OrdersDetails (order_id, product_id, quantity) values ('1', '2', '10'); +insert into OrdersDetails (order_id, product_id, quantity) values ('1', '3', '15'); +insert into OrdersDetails (order_id, product_id, quantity) values ('2', '1', '8'); +insert into OrdersDetails (order_id, product_id, quantity) values ('2', '4', '4'); +insert into OrdersDetails (order_id, product_id, quantity) values ('2', '5', '6'); +insert into OrdersDetails (order_id, product_id, quantity) values ('3', '3', '5'); +insert into OrdersDetails (order_id, product_id, quantity) values ('3', '4', '18'); +insert into OrdersDetails (order_id, product_id, quantity) values ('4', '5', '2'); +insert into OrdersDetails (order_id, product_id, quantity) values ('4', '6', '8'); +insert into OrdersDetails (order_id, product_id, quantity) values ('5', '7', '9'); +insert into OrdersDetails (order_id, product_id, quantity) values ('5', '8', '9'); +insert into OrdersDetails (order_id, product_id, quantity) values ('3', '9', '20'); +insert into OrdersDetails (order_id, product_id, quantity) values ('2', '9', '4'); diff --git a/problems/pacific-atlantic-water-flow/README.md b/problems/pacific-atlantic-water-flow/README.md index 2c5427e2f..e886a0a69 100644 --- a/problems/pacific-atlantic-water-flow/README.md +++ b/problems/pacific-atlantic-water-flow/README.md @@ -39,7 +39,7 @@Example 2:
- --Input: text = "we will we will rock you", first = "we", second = "will" -Output: ["we","rock"] --+
Constraints:
-Note:
- -+
-
- -
1 <= text.length <= 1000
- +
text
consists of space separated words, where each word consists of lowercase English letters.- +
text
consists of lowercase English letters and spaces.- All the words in
text
a separated by a single space.1 <= first.length, second.length <= 10
- -
first
andsecond
consist of lowercase English letters.
m == heights.length
n == heights[i].length
1 <= m, n <= 200
1 <= heights[i][j] <= 105
0 <= heights[i][j] <= 105
Given the integer n
representing the number of courses at some university labeled from 1
to n
, and the array dependencies
where dependencies[i] = [xi, yi]
represents a prerequisite relationship, that is, the course xi
must be taken before the course yi
. Also, you are given the integer k
.
You are given an integer n
, which indicates that there are n
courses labeled from 1
to n
. You are also given an array relations
where relations[i] = [prevCoursei, nextCoursei]
, representing a prerequisite relationship between course prevCoursei
and course nextCoursei
: course prevCoursei
has to be taken before course nextCoursei
. Also, you are given the integer k
.
In one semester you can take at most k
courses as long as you have taken all the prerequisites for the courses you are taking.
In one semester, you can take at most k
courses as long as you have taken all the prerequisites in the previous semester for the courses you are taking.
Return the minimum number of semesters to take all courses. It is guaranteed that you can take all courses in some way.
+Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.
Example 1:
@@ -25,7 +25,10 @@Input: n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2 Output: 3 -Explanation: The figure above represents the given graph. In this case we can take courses 2 and 3 in the first semester, then take course 1 in the second semester and finally take course 4 in the third semester. +Explanation: The figure above represents the given graph. +In the first semester, you can take courses 2 and 3. +In the second semester, you can take course 1. +In the third semester, you can take course 4.
Example 2:
@@ -35,7 +38,11 @@Input: n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2 Output: 4 -Explanation: The figure above represents the given graph. In this case one optimal way to take all courses is: take courses 2 and 3 in the first semester and take course 4 in the second semester, then take course 1 in the third semester and finally take course 5 in the fourth semester. +Explanation: The figure above represents the given graph. +In the first semester, you can take courses 2 and 3 only since you cannot take more than two per semester. +In the second semester, you can take course 4. +In the third semester, you can take course 1. +In the fourth semester, you can take course 5.
Example 3:
@@ -51,11 +58,11 @@1 <= n <= 15
1 <= k <= n
0 <= dependencies.length <= n * (n-1) / 2
dependencies[i].length == 2
1 <= xi, yi <= n
xi != yi
dependencies[i] != dependencies[j]
.0 <= relations.length <= n * (n-1) / 2
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
[prevCoursei, nextCoursei]
are unique.1 <= k <= nums.length <= 16
0 <= nums[i] <= 104
1 <= nums[i] <= 104
[1, 4]
.Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
Print a binary tree in an m x n
2D string array following these rules:
Given the root
of a binary tree, construct a 0-indexed m x n
string matrix res
that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
m
should be equal to the height of the given binary tree.n
should always be an odd number.""
.height
and the number of rows m
should be equal to height + 1
.n
should be equal to 2height+1 - 1
.res[0][(n-1)/2]
).res[r][c]
, place its left child at res[r+1][c-2height-r-1]
and its right child at res[r+1][c+2height-r-1]
.""
.Return the constructed matrix res
.
Example 1:
You are given two 0-indexed integer arrays servers
and tasks
of lengths n
and m
respectively. servers[i]
is the weight of the ith
server, and tasks[j]
is the time needed to process the jth
task in seconds.
Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.
+ +At second j
, the jth
task is inserted into the queue (starting with the 0th
task being inserted at second 0
). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.
+ +A server that is assigned task j
at second t
will be free again at second t + tasks[j]
.
Build an array ans
of length m
, where ans[j]
is the index of the server the jth
task will be assigned to.
Return the array ans
.
+
Example 1:
+ ++Input: servers = [3,3,2], tasks = [1,2,3,2,1,2] +Output: [2,2,0,2,1,2] +Explanation: Events in chronological order go as follows: +- At second 0, task 0 is added and processed using server 2 until second 1. +- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3. +- At second 2, task 2 is added and processed using server 0 until second 5. +- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5. +- At second 4, task 4 is added and processed using server 1 until second 5. +- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.+ +
Example 2:
+ ++Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1] +Output: [1,4,1,4,1,3,2] +Explanation: Events in chronological order go as follows: +- At second 0, task 0 is added and processed using server 1 until second 2. +- At second 1, task 1 is added and processed using server 4 until second 2. +- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. +- At second 3, task 3 is added and processed using server 4 until second 7. +- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. +- At second 5, task 5 is added and processed using server 3 until second 7. +- At second 6, task 6 is added and processed using server 2 until second 7. ++ +
+
Constraints:
+ +servers.length == n
tasks.length == m
1 <= n, m <= 2 * 105
1 <= servers[i], tasks[j] <= 2 * 105
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
.
Given the output traversal
of this traversal, recover the tree and return its root
.
Example 1:
-Input: S = "1-2--3--4-5--6--7" +Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7]
Example 2:
-Input: S = "1-2--3---4-5--6---7" +Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7]
Example 3:
-Input: S = "1-401--349---90--88" +Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90]diff --git a/problems/regions-cut-by-slashes/README.md b/problems/regions-cut-by-slashes/README.md index 920a4ff39..310bbcee9 100644 --- a/problems/regions-cut-by-slashes/README.md +++ b/problems/regions-cut-by-slashes/README.md @@ -11,112 +11,59 @@ ## [959. Regions Cut By Slashes (Medium)](https://leetcode.com/problems/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.
An n x n
grid is composed of 1 x 1
squares where 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 "\\"
.)
Given the grid grid
represented as a string array, return the number of regions.
Return the number of regions.
+Note that backslash characters are escaped, so a '\'
is represented as '\\'
.
- -
Example 1:
- +-Input: -[ - " /", - "/ " -] -Output: 2 -Explanation: The 2x2 grid is as follows: --+Input: grid = [" /","/ "] +Output: 2
Example 2:
- +-Input: -[ - " /", - " " -] -Output: 1 -Explanation: The 2x2 grid is as follows: --+Input: grid = [" /"," "] +Output: 1
Example 3:
- +-Input: -[ - "\\/", - "/\\" -] -Output: 4 +Input: grid = ["\\/","/\\"] +Output: 4 Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.) -The 2x2 grid is as follows: --![]()
Example 4:
- +-Input: -[ - "/\\", - "\\/" -] -Output: 5 -Explanation: (Recall that because \ characters are escaped, "/\\" refers to /\, and "\\/" refers to \/.) -The 2x2 grid is as follows: --+Input: grid = ["/\\","\\/"] +Output: 5 +Explanation: (Recall that because \ characters are escaped, "\\/" refers to \/, and "/\\" refers to /\.)
Example 5:
- +-Input: -[ - "//", - "/ " -] -Output: 3 -Explanation: The 2x2 grid is as follows: -+Input: grid = ["//","/ "] +Output: 3
+
Constraints:
-Note:
- -1 <= grid.length == grid[0].length <= 30
n == grid.length
n == grid[i].length
1 <= n <= 30
grid[i][j]
is either '/'
, '\'
, or ' '
.You are given a string s
. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
You are given a string s
consisting of lowercase English 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.
+Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
diff --git a/problems/remove-duplicates-from-sorted-array/README.md b/problems/remove-duplicates-from-sorted-array/README.md index 461920620..47d098adc 100644 --- a/problems/remove-duplicates-from-sorted-array/README.md +++ b/problems/remove-duplicates-from-sorted-array/README.md @@ -30,8 +30,9 @@ 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]); -} + print(nums[i]); +} +
Example 1:
diff --git a/problems/remove-outermost-parentheses/README.md b/problems/remove-outermost-parentheses/README.md index c087df718..72901c984 100644 --- a/problems/remove-outermost-parentheses/README.md +++ b/problems/remove-outermost-parentheses/README.md @@ -13,18 +13,18 @@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.
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.
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
.
Return s
after removing the outermost parentheses of every primitive string in the primitive decomposition of S
.
Example 1:
-Input: "(()())(())" +Input: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". @@ -35,7 +35,7 @@ After removing outer parentheses of each part, this is "()()" + "Example 2:
-Input: "(()())(())(()(()))" +Input: s = "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". @@ -46,7 +46,7 @@ After removing outer parentheses of each part, this is "()()" + "Example 3:
-Input: "()()" +Input: s = "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". @@ -60,9 +60,9 @@ After removing outer parentheses of each part, this is "" + "&quoNote:
-
- -
S.length <= 10000
- -
S[i]
is"("
or")"
- +
S
is a valid parentheses string- +
s.length <= 10000
- +
s[i]
is"("
or")"
s
is a valid parentheses stringdiff --git a/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md b/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md index 8740e846e..23a90d09d 100644 --- a/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md +++ b/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/README.md @@ -11,34 +11,32 @@ ## [1466. Reorder Routes to Make All Paths Lead to the City Zero (Medium)](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero "重新规划路线") -diff --git a/problems/rle-iterator/README.md b/problems/rle-iterator/README.md index 272eb72d3..8533fc735 100644 --- a/problems/rle-iterator/README.md +++ b/problems/rle-iterator/README.md @@ -11,46 +11,50 @@ ## [900. RLE Iterator (Medium)](https://leetcode.com/problems/rle-iterator "RLE 迭代器") -There are
+n
cities numbered from0
ton-1
andn-1
roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.There are
-n
cities numbered from0
ton - 1
andn - 1
roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.Roads are represented by
+connections
whereconnections[i] = [a, b]
represents a road from citya
tob
.Roads are represented by
-connections
whereconnections[i] = [ai, bi]
represents a road from cityai
to citybi
.This year, there will be a big event in the capital (city 0), and many people want to travel to this city.
+This year, there will be a big event in the capital (city
-0
), and many people want to travel to this city.Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.
+Your task consists of reorienting some roads such that each city can visit the city
-0
. Return the minimum number of edges changed.It's guaranteed that each city can reach the city 0 after reorder.
+It's guaranteed that each city can reach city
0
after reorder.
Example 1:
- -- +
Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 -Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).+Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). +Example 2:
- -- +
Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]] Output: 2 -Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).+Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital). +Example 3:
@@ -51,11 +49,11 @@Constraints:
-
### Related Topics diff --git a/problems/restore-ip-addresses/README.md b/problems/restore-ip-addresses/README.md index cb6a583eb..e236a5367 100644 --- a/problems/restore-ip-addresses/README.md +++ b/problems/restore-ip-addresses/README.md @@ -45,4 +45,4 @@ [[Backtracking](../../tag/backtracking/README.md)] ### Similar Questions - 1. [IP to CIDR](../ip-to-cidr) (Easy) + 1. [IP to CIDR](../ip-to-cidr) (Medium) diff --git a/problems/reveal-cards-in-increasing-order/README.md b/problems/reveal-cards-in-increasing-order/README.md index 91b50b6a2..b4783978a 100644 --- a/problems/reveal-cards-in-increasing-order/README.md +++ b/problems/reveal-cards-in-increasing-order/README.md @@ -36,7 +36,7 @@ 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. +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]. @@ -54,9 +54,9 @@ Since all the cards revealed are in increasing order, the answer is correct.- -
2 <= n <= 5 * 10^4
- +
connections.length == n-1
- +
2 <= n <= 5 * 104
connections.length == n - 1
- -
connections[i].length == 2
- -
0 <= connections[i][0], connections[i][1] <= n-1
- +
connections[i][0] != connections[i][1]
- +
0 <= ai, bi <= n - 1
ai != bi
Note:
-
- -
1 <= A.length <= 1000
- -
1 <= A[i] <= 10^6
- +
A[i] != A[j]
for alli != j
- +
1 <= deck.length <= 1000
- +
1 <= deck[i] <= 10^6
deck[i] != deck[j]
for alli != j
Write an iterator that iterates through a run-length encoded sequence.
+We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length
-encoding
(0-indexed), for all eveni
,encoding[i]
tells us the number of times that the non-negative integer valueencoding[i + 1]
is repeated in the sequence.The iterator is initialized by
+RLEIterator(int[] encoding)
, whereencoding
is a run-length encoding of some sequence. More specifically, for all eveni
,encoding[i]
tells us the number of times that the non-negative integer valueencoding[i+1]
is repeated in the sequence.
arr = [8,8,8,5,5]
can be encoded to be encoding = [3,8,2,5]
. encoding = [3,8,0,9,2,5]
and encoding = [2,8,1,8,2,5]
are also valid RLE of arr
.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.
Given a run-length encoded array, design an iterator that iterates through it.
-For example, we start with encoding = [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".
Implement the RLEIterator
class:
+
RLEIterator(int[] encoded)
Initializes the object with the encoded array encoded
.int next(int n)
Exhausts the next n
elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1
instead.
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. - +Input +["RLEIterator", "next", "next", "next", "next"] +[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]] +Output +[null, 8, 8, 5, -1] + +Explanation +RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5]. +rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5]. +rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5]. +rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5]. +rLEIterator.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:
++
Constraints:
-0 <= encoding.length <= 1000
encoding.length
is an even integer.2 <= encoding.length <= 1000
encoding.length
is even.0 <= encoding[i] <= 109
1000
calls to RLEIterator.next(int n)
per test case.RLEIterator.next(int n)
will have 1 <= n <= 109
.1 <= n <= 109
1000
calls will be made to next
.n == nums.length
1 <= n <= 105
1 <= n <= 3 * 104
-231 <= nums[i] <= 231 - 1
You are given an n x n 2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
You are given an n x n
2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
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.
diff --git a/problems/rotating-the-box/README.md b/problems/rotating-the-box/README.md new file mode 100644 index 000000000..a086e537e --- /dev/null +++ b/problems/rotating-the-box/README.md @@ -0,0 +1,92 @@ + + + + + + + +[< Previous](../incremental-memory-leak "Incremental Memory Leak") + +[Next >](../sum-of-floored-pairs "Sum of Floored Pairs") + +## [1861. Rotating the Box (Medium)](https://leetcode.com/problems/rotating-the-box "旋转盒子") + +You are given an m x n
matrix of characters box
representing a side-view of a box. Each cell of the box is one of the following:
'#'
'*'
'.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
+ +It is guaranteed that each stone in box
rests on an obstacle, another stone, or the bottom of the box.
Return an n x m
matrix representing the box after the rotation described above.
+
Example 1:
+ ++Input: box = [["#",".","#"]] +Output: [["."], + ["#"], + ["#"]] ++ +
Example 2:
+ ++Input: box = [["#",".","*","."], + ["#","#","*","."]] +Output: [["#","."], + ["#","#"], + ["*","*"], + [".","."]] ++ +
Example 3:
+ ++Input: box = [["#","#","*",".","*","."], + ["#","#","#","*",".","."], + ["#","#","#",".","#","."]] +Output: [[".","#","#"], + [".","#","#"], + ["#","#","*"], + ["#","*","."], + ["#",".","*"], + ["#",".","."]] ++ +
+
Constraints:
+ +m == box.length
n == box[i].length
1 <= m, n <= 500
box[i][j]
is either '#'
, '*'
, or '.'
.Given the array nums
after the rotation and an integer target
, return true
if target
is in nums
, or false
if it is not in nums
.
You must decrease the overall operation steps as much as possible.
+
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0 @@ -36,7 +38,7 @@-Follow up: This problem is the same as Search in Rotated Sorted Array, where
nums
may contain duplicates. Would this affect the runtime complexity? How and why? +Follow up: This problem is similar to Search in Rotated Sorted Array, but
### Related Topics [[Array](../../tag/array/README.md)] diff --git a/problems/self-crossing/README.md b/problems/self-crossing/README.md index 1540d2e0c..d05b7ca32 100644 --- a/problems/self-crossing/README.md +++ b/problems/self-crossing/README.md @@ -43,12 +43,9 @@nums
may contain duplicates. Would this affect the runtime complexity? How and why?Constraints:
1 <= distance.length <= 500
1 <= distance[i] <= 500
1 <= distance.length <= 105
1 <= distance[i] <= 105
-
Follow up: Could you write a one-pass algorithm with O(1)
extra space?
-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] +A self-dividing number is a number that is divisible by every digit it contains.
+ +
128
is a self-dividing number because 128 % 1 == 0
, 128 % 2 == 0
, and 128 % 8 == 0
.A self-dividing number is not allowed to contain the digit zero.
+ +Given two integers left
and right
, return a list of all the self-dividing numbers in the range [left, right]
.
+
Example 1:
+Input: left = 1, right = 22 +Output: [1,2,3,4,5,6,7,8,9,11,12,15,22] +
Example 2:
+Input: left = 47, right = 85 +Output: [48,55,66,77]- +
+
Constraints:
-Note: -
1 <= left <= right <= 10000
.1 <= left <= right <= 104
Given a positive integer K
, you need to find the length of the smallest positive integer N
such that N
is divisible by K
, and N
only contains the digit 1
.
Given a positive integer k
, you need to find the length of 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.
Return the length of n
. If there is no such n
, return -1.
Note: N
may not fit in a 64-bit signed integer.
Note: n
may not fit in a 64-bit signed integer.
Example 1:
-Input: K = 1 +Input: k = 1 Output: 1 -Explanation: The smallest answer is N = 1, which has length 1. +Explanation: The smallest answer is n = 1, which has length 1.
Example 2:
-Input: K = 2 +Input: k = 2 Output: -1 -Explanation: There is no such positive integer N divisible by 2. +Explanation: There is no such positive integer n divisible by 2.
Example 3:
-Input: K = 3 +Input: k = 3 Output: 3 -Explanation: The smallest answer is N = 111, which has length 3. +Explanation: The smallest answer is n = 111, which has length 3.
Constraints:
1 <= K <= 105
1 <= k <= 105
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
+ +A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
+ +"This is a sentence"
can be shuffled as "sentence4 a3 is2 This1"
or "is2 sentence4 This1 a3"
.Given a shuffled sentence s
containing no more than 9
words, reconstruct and return the original sentence.
+
Example 1:
+ ++Input: s = "is2 sentence4 This1 a3" +Output: "This is a sentence" +Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers. ++ +
Example 2:
+ ++Input: s = "Myself2 Me1 I4 and3" +Output: "Me Myself and I" +Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers. ++ +
+
Constraints:
+ +2 <= s.length <= 200
s
consists of lowercase and uppercase English letters, spaces, and digits from 1
to 9
.s
is between 1
and 9
.s
are separated by a single space.s
contains no leading or trailing spaces.Given an integer array nums
that is sorted in ascending order, return true
if and only if you can split it into one or more subsequences such that each subsequence consists of consecutive integers and has a length of at least 3
.
You are given an integer array nums
that is sorted in non-decreasing order.
Determine if it is possible to split nums
into one or more subsequences such that both of the following conditions are true:
3
or more.Return true
if you can split nums
according to the above conditions, or false
otherwise.
A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5]
is a subsequence of [1,2,3,4,5]
while [1,3,2]
is not).
Example 1:
@@ -19,10 +30,9 @@Input: nums = [1,2,3,3,4,5] Output: true -Explanation: -You can split them into two consecutive subsequences : -1, 2, 3 -3, 4, 5 +Explanation: nums can be split into the following subsequences: +[1,2,3,3,4,5] --> 1, 2, 3 +[1,2,3,3,4,5] --> 3, 4, 5
Example 2:
@@ -30,10 +40,9 @@ You can split them into two consecutive subsequences :Input: nums = [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 +Explanation: nums can be split into the following subsequences: +[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 +[1,2,3,3,4,4,5,5] --> 3, 4, 5
Example 3:
@@ -41,6 +50,7 @@ You can split them into two consecutive subsequences :Input: nums = [1,2,3,4,4,5] Output: false +Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
@@ -49,7 +59,7 @@ You can split them into two consecutive subsequences :
1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
nums
is sorted in an ascending order.nums
is sorted in non-decreasing order.Given a string num
of digits, such as num = "123456579"
, we can split it into a Fibonacci-like sequence [123, 456, 579].
You are given a string of digits num
, such as "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:
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
; F[i] + F[i+1] = F[i+2]
for all 0 <= i < F.length - 2
.0 <= f[i] < 231
, (that is, each integer fits in a 32-bit signed integer type),f.length >= 3
, andf[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.
+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 num
, or return []
if it cannot be done.
Example 1:
-Input: num = "123456579" -Output: [123,456,579] +Input: num = "123456579" +Output: [123,456,579]
Example 2:
-Input: num = "11235813" -Output: [1,1,2,3,5,8,13] +Input: num = "11235813" +Output: [1,1,2,3,5,8,13]
Example 3:
-Input: num = "112358130" -Output: [] -Explanation: The task is impossible. +Input: num = "112358130" +Output: [] +Explanation: The task is impossible.
Example 4:
-Input: num = "0123" -Output: [] -Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid. +Input: num = "0123" +Output: [] +Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Example 5:
-Input: num = "1101111" -Output: [110, 1, 111] -Explanation: The output [11, 0, 11, 11] would also be accepted. +Input: num = "1101111" +Output: [11,0,11,11] +Explanation: The output [11, 0, 11, 11] would also be accepted.-
Note:
++
Constraints:
-1 <= num.length <= 200
1 <= num.length <= 200
num
contains only digits.Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
+Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5)
or x ** 0.5
.
Example 1:
diff --git a/problems/stone-game-viii/README.md b/problems/stone-game-viii/README.md new file mode 100644 index 000000000..9d33ad575 --- /dev/null +++ b/problems/stone-game-viii/README.md @@ -0,0 +1,87 @@ + + + + + + + +[< Previous](../jump-game-vii "Jump Game VII") + +[Next >](../calculate-special-bonus "Calculate Special Bonus") + +## [1872. Stone Game VIII (Hard)](https://leetcode.com/problems/stone-game-viii "石子游戏 VIII") + +Alice and Bob take turns playing a game, with Alice starting first.
+ +There are n
stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:
x > 1
, and remove the leftmost x
stones from the row.The game stops when only one stone is left in the row.
+ +The score difference between Alice and Bob is (Alice's score - Bob's score)
. Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.
Given an integer array stones
of length n
where stones[i]
represents the value of the ith
stone from the left, return the score difference between Alice and Bob if they both play optimally.
+
Example 1:
+ ++Input: stones = [-1,2,-3,4,-5] +Output: 5 +Explanation: +- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of + value 2 on the left. stones = [2,-5]. +- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on + the left. stones = [-3]. +The difference between their scores is 2 - (-3) = 5. ++ +
Example 2:
+ ++Input: stones = [7,-6,5,10,5,-2,-6] +Output: 13 +Explanation: +- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a + stone of value 13 on the left. stones = [13]. +The difference between their scores is 13 - 0 = 13. ++ +
Example 3:
+ ++Input: stones = [-10,-12] +Output: -22 +Explanation: +- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her + score and places a stone of value -22 on the left. stones = [-22]. +The difference between their scores is (-22) - 0 = -22. ++ +
+
Constraints:
+ +n == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104
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
.
Given an array of integers nums
and an integer k
, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k
.
+
Example 1:
-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]. +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
.0 < nums[i] < 1000
.0 <= k < 10^6
.Example 2:
+ ++Input: nums = [1,2,3], k = 0 +Output: 0 ++ +
+
Constraints:
+ +1 <= nums.length <= 105
0 <= nums[i] < 1000
0 <= k < 106
A string is good if there are no repeated characters.
+ +Given a string s
, return the number of good substrings of length three in s
.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
+ +A substring is a contiguous sequence of characters in a string.
+ ++
Example 1:
+ ++Input: s = "xyzzaz" +Output: 1 +Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". +The only good substring of length 3 is "xyz". ++ +
Example 2:
+ ++Input: s = "aababcabc" +Output: 4 +Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". +The good substrings are "abc", "bca", "cab", and "abc". ++ +
+
Constraints:
+ +1 <= s.length <= 100
s
consists of lowercase English letters.Example 2:
-Input: root = [3,4,5,1,2,null,null,0], subRoot = [4,1,2] +Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] Output: falsediff --git a/problems/sum-of-all-subset-xor-totals/README.md b/problems/sum-of-all-subset-xor-totals/README.md new file mode 100644 index 000000000..a017f0ec1 --- /dev/null +++ b/problems/sum-of-all-subset-xor-totals/README.md @@ -0,0 +1,86 @@ + + + + + + + +[< Previous](../sum-of-floored-pairs "Sum of Floored Pairs") + +[Next >](../minimum-number-of-swaps-to-make-the-binary-string-alternating "Minimum Number of Swaps to Make the Binary String Alternating") + +## [1863. Sum of All Subset XOR Totals (Easy)](https://leetcode.com/problems/sum-of-all-subset-xor-totals "找出所有子集的异或总和再求和") + +
The XOR total of an array is defined as the bitwise XOR
of all its elements, or 0
if the array is empty.
[2,5,6]
is 2 XOR 5 XOR 6 = 1
.Given an array nums
, return the sum of all XOR totals for every subset of nums
.
Note: Subsets with the same elements should be counted multiple times.
+ +An array a
is a subset of an array b
if a
can be obtained from b
by deleting some (possibly zero) elements of b
.
+
Example 1:
+ ++Input: nums = [1,3] +Output: 6 +Explanation: The 4 subsets of [1,3] are: +- The empty subset has an XOR total of 0. +- [1] has an XOR total of 1. +- [3] has an XOR total of 3. +- [1,3] has an XOR total of 1 XOR 3 = 2. +0 + 1 + 3 + 2 = 6 ++ +
Example 2:
+ ++Input: nums = [5,1,6] +Output: 28 +Explanation: The 8 subsets of [5,1,6] are: +- The empty subset has an XOR total of 0. +- [5] has an XOR total of 5. +- [1] has an XOR total of 1. +- [6] has an XOR total of 6. +- [5,1] has an XOR total of 5 XOR 1 = 4. +- [5,6] has an XOR total of 5 XOR 6 = 3. +- [1,6] has an XOR total of 1 XOR 6 = 7. +- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2. +0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 ++ +
Example 3:
+ ++Input: nums = [3,4,5,6,7,8] +Output: 480 +Explanation: The sum of all XOR totals for every subset is 480. ++ +
+
Constraints:
+ +1 <= nums.length <= 12
1 <= nums[i] <= 20
Given an integer array nums
, return the sum of floor(nums[i] / nums[j])
for all pairs of indices 0 <= i, j < nums.length
in the array. Since the answer may be too large, return it modulo 109 + 7
.
The floor()
function returns the integer part of the division.
+
Example 1:
+ ++Input: nums = [2,5,9] +Output: 10 +Explanation: +floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 +floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 +floor(5 / 2) = 2 +floor(9 / 2) = 4 +floor(9 / 5) = 1 +We calculate the floor of the division for every pair of indices in the array then sum them up. ++ +
Example 2:
+ ++Input: nums = [7,7,7,7,7,7,7] +Output: 49 ++ +
+
Constraints:
+ +1 <= nums.length <= 105
1 <= nums[i] <= 105
You are given an integer array timeSeries
and an integer duration
. Our hero Teemo has attacked an enemy where the ith
attack was done at the timeSeries[i]
. When Teemo attacks their enemy, the enemy gets poisoned for duration
time (i.e., the enemy is poisoned for the time interval [timeSeries[i], timeSeries[i] + duration - 1]
inclusive).
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration
seconds. More formally, an attack at second t
will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]
. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration
seconds after the new attack.
Return the total time that the enemy is in a poisoned condition.
+You are given a non-decreasing integer array timeSeries
, where timeSeries[i]
denotes that Teemo attacks Ashe at second timeSeries[i]
, and an integer duration
.
Return the total number of seconds that Ashe is poisoned.
Example 1:
@@ -21,10 +23,10 @@Input: timeSeries = [1,4], duration = 2 Output: 4 -Explanation: At time point 1, Teemo starts attacking the enemy and makes them be poisoned immediately. -This poisoned status will last 2 seconds until the end of time point 2. -And at time point 4, Teemo attacks the enemy again and causes them to be in poisoned status for another 2 seconds. -So you finally need to output 4. +Explanation: Teemo's attacks on Ashe go as follows: +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. +- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5. +Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
Example 2:
@@ -32,12 +34,10 @@ So you finally need to output 4.Input: timeSeries = [1,2], duration = 2 Output: 3 -Explanation: At time point 1, Teemo starts attacking the enemy and makes them 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 the enemy 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. -+Explanation: Teemo's attacks on Ashe go as follows: +- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2. +- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3. +Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
Constraints:
@@ -45,7 +45,7 @@ So you finally need to output 3.1 <= timeSeries.length <= 104
0 <= timeSeries[i], duration <= 107
timeSeries
is sorted in non-decreasing order.timeSeries
is sorted in non-decreasing order.Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
+Given a string s
, return the string after replacing every uppercase letter with the same lowercase letter.
- -
Example 1:
-Input: "Hello" -Output: "hello" +Input: s = "Hello" +Output: "hello"-
Example 2:
-Input: "here" -Output: "here" +Input: s = "here" +Output: "here"-
Example 3:
-Input: "LOVELY" -Output: "lovely" +Input: s = "LOVELY" +Output: "lovely"-
+
Constraints:
+ +1 <= s.length <= 100
s
consists of printable ASCII characters.Given an array of integers numbers
that is already sorted in ascending order, find two numbers such that they add up to a specific target
number.
Given an array of integers numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target
number.
Return the indices of the two numbers (1-indexed) as an integer array answer
of size 2
, where 1 <= answer[0] < answer[1] <= numbers.length
.
Return the indices of the two numbers (1-indexed) as an integer array answer
of size 2
, where 1 <= answer[0] < answer[1] <= numbers.length
.
You may assume that each input would have exactly one solution and you may not use the same element twice.
+The tests are generated such that there is exactly one solution. You may not use the same element twice.
Example 1:
@@ -46,9 +46,9 @@2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers
is sorted in increasing order.numbers
is sorted in non-decreasing order.-1000 <= target <= 1000
Constraints:
2 <= nums.length <= 103
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
+Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
+
### Related Topics
[[Array](../../tag/array/README.md)]
[[Hash Table](../../tag/hash-table/README.md)]
diff --git a/problems/uncrossed-lines/README.md b/problems/uncrossed-lines/README.md
index 8d9366fb0..036421171 100644
--- a/problems/uncrossed-lines/README.md
+++ b/problems/uncrossed-lines/README.md
@@ -11,12 +11,12 @@
## [1035. Uncrossed Lines (Medium)](https://leetcode.com/problems/uncrossed-lines "不相交的线")
-We write the integers of A
and B
(in the order they are given) on two separate horizontal lines.
We write the integers of nums1
and nums2
(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:
Now, we may draw connecting lines: a straight line connecting two numbers nums1[i]
and nums2[j]
such that:
A[i] == B[j]
;nums1[i] == nums2[j]
;Example 1:
-Input: A = [1,4,2], B = [1,2,4] +Input: nums1 = [1,4,2], nums2 = [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. +We cannot draw 3 uncrossed lines, because the line from nums1[1]=4 to nums2[2]=4 will intersect the line from nums1[2]=2 to nums2[1]=2.
Example 2:
-Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2] +Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] Output: 3@@ -47,7 +47,7 @@ We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will in
Example 3:
-Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1] +Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] Output: 2
@@ -57,9 +57,9 @@ We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will in
Note:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
1 <= nums1.length <= 500
1 <= nums2.length <= 500
1 <= nums1[i], nums2[i] <= 2000
'+'
or '-'
).'.'
.'.'
, followed by at least one digit.'.'
, followed by at least one digit.'.'
.'.'
, followed by one or more digits.'.'
, followed by one or more digits.'+'
or '-'
).For example, all the following are valid numbers: ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]
, while the following are not valid numbers: ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]
.
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.
Given a Tic-Tac-Toe board 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.
The board is a 3 x 3
array that consists of characters ' '
, 'X'
, and 'O'
. The ' '
character represents an empty square.
Here are the rules of Tic-Tac-Toe:
' '
.'X'
characters, while the second player always places 'O'
characters.'X'
and 'O'
characters are always placed into empty squares, never filled ones.+
Example 1:
+-Example 1: -Input: board = ["O ", " ", " "] +Input: board = ["O "," "," "] Output: false -Explanation: The first player always plays "X". +Explanation: The first player always plays "X". +-Example 2: -Input: board = ["XOX", " X ", " "] +
Example 2:
++Input: board = ["XOX"," X "," "] Output: false -Explanation: Players take turns making moves. +Explanation: Players take turns making moves. +-Example 3: -Input: board = ["XXX", " ", "OOO"] +
Example 3:
++Input: board = ["XXX"," ","OOO"] Output: false +-Example 4: -Input: board = ["XOX", "O O", "XOX"] +
Example 4:
++Input: board = ["XOX","O O","XOX"] Output: true-
Note:
++
Constraints:
board
is a length-3 array of strings, where each string board[i]
has length 3.board[i][j]
is a character in the set {" ", "X", "O"}
.board.length == 3
board[i].length == 3
board[i][j]
is either 'X'
, 'O'
, or ' '
."1,,3"
.Note: You are not allowed to reconstruct the tree.
+
Example 1:
Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" @@ -44,8 +46,5 @@
preoder
consist of integers in the range [0, 100]
and '#'
separated by commas ','
.-
Follow up: Find an algorithm without reconstructing the tree.
- ### Related Topics [[Stack](../../tag/stack/README.md)] diff --git a/problems/video-stitching/README.md b/problems/video-stitching/README.md index 5e0050992..79bb66793 100644 --- a/problems/video-stitching/README.md +++ b/problems/video-stitching/README.md @@ -11,20 +11,25 @@ ## [1024. Video Stitching (Medium)](https://leetcode.com/problems/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.
You are given a series of video clips from a sporting event that lasted time
seconds. These video clips can be overlapping with each other and have varying 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]
.
Each video clip is described by an array clips
where clips[i] = [starti, endi]
indicates that the ith clip started at starti
and ended at endi
.
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
.
We can cut these clips into segments freely.
-+
[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, time]
. 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: +Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 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]. @@ -34,28 +39,25 @@ Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 1Example 2:
-Input: clips = [[0,1],[1,2]], T = 5 -Output: -1 -Explanation: -We can't cover [0,5] with only [0,1] and [1,2]. +Input: clips = [[0,1],[1,2]], time = 5 +Output: -1 +Explanation: We can't cover [0,5] with only [0,1] and [1,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]. +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]], time = 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. +Input: clips = [[0,4],[2,8]], time = 5 +Output: 2 +Explanation: Notice you can have extra video after the event ends.@@ -63,8 +65,8 @@ Notice you can have extra video after the event ends.
1 <= clips.length <= 100
0 <= clips[i][0] <= clips[i][1] <= 100
0 <= T <= 100
0 <= clips[i][0] <= clips[i][1] <= 100
1 <= time <= 100