diff --git a/README.md b/README.md index e8fc2478e..8808bc253 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,22 @@ LeetCode Problems' Solutions | # | Title | Solution | Difficulty | | :-: | - | - | :-: | +| 1819 | [Number of Different Subsequences GCDs](https://leetcode.com/problems/number-of-different-subsequences-gcds "序列中不同最大公约数的数目") | [Go](problems/number-of-different-subsequences-gcds) | Hard | +| 1818 | [Minimum Absolute Sum Difference](https://leetcode.com/problems/minimum-absolute-sum-difference "绝对差值和") | [Go](problems/minimum-absolute-sum-difference) | Medium | +| 1817 | [Finding the Users Active Minutes](https://leetcode.com/problems/finding-the-users-active-minutes "查找用户活跃分钟数") | [Go](problems/finding-the-users-active-minutes) | Medium | +| 1816 | [Truncate Sentence](https://leetcode.com/problems/truncate-sentence "截断句子") | [Go](problems/truncate-sentence) | Easy | +| 1815 | [Maximum Number of Groups Getting Fresh Donuts](https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts "得到新鲜甜甜圈的最多组数") | [Go](problems/maximum-number-of-groups-getting-fresh-donuts) | Hard | +| 1814 | [Count Nice Pairs in an Array](https://leetcode.com/problems/count-nice-pairs-in-an-array "统计一个数组中好对子的数目") | [Go](problems/count-nice-pairs-in-an-array) | Medium | +| 1813 | [Sentence Similarity III](https://leetcode.com/problems/sentence-similarity-iii "句子相似性 III") | [Go](problems/sentence-similarity-iii) | Medium | +| 1812 | [Determine Color of a Chessboard Square](https://leetcode.com/problems/determine-color-of-a-chessboard-square "判断国际象棋棋盘中一个格子的颜色") | [Go](problems/determine-color-of-a-chessboard-square) | Easy | +| 1811 | [Find Interview Candidates](https://leetcode.com/problems/find-interview-candidates) 🔒 | [MySQL](problems/find-interview-candidates) | Medium | +| 1810 | [Minimum Path Cost in a Hidden Grid](https://leetcode.com/problems/minimum-path-cost-in-a-hidden-grid) 🔒 | [Go](problems/minimum-path-cost-in-a-hidden-grid) | Medium | +| 1809 | [Ad-Free Sessions](https://leetcode.com/problems/ad-free-sessions) 🔒 | [MySQL](problems/ad-free-sessions) | Easy | +| 1808 | [Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors "好因子的最大数目") | [Go](problems/maximize-number-of-nice-divisors) | Hard | +| 1807 | [Evaluate the Bracket Pairs of a String](https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string "替换字符串中的括号内容") | [Go](problems/evaluate-the-bracket-pairs-of-a-string) | Medium | +| 1806 | [Minimum Number of Operations to Reinitialize a Permutation](https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation "还原排列的最少操作步数") | [Go](problems/minimum-number-of-operations-to-reinitialize-a-permutation) | Medium | +| 1805 | [Number of Different Integers in a String](https://leetcode.com/problems/number-of-different-integers-in-a-string "字符串中不同整数的数目") | [Go](problems/number-of-different-integers-in-a-string) | Easy | +| 1804 | [Implement Trie II (Prefix Tree)](https://leetcode.com/problems/implement-trie-ii-prefix-tree) 🔒 | [Go](problems/implement-trie-ii-prefix-tree) | Medium | | 1803 | [Count Pairs With XOR in a Range](https://leetcode.com/problems/count-pairs-with-xor-in-a-range "统计异或值在范围内的数对有多少") | [Go](problems/count-pairs-with-xor-in-a-range) | Hard | | 1802 | [Maximum Value at a Given Index in a Bounded Array](https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array "有界数组中指定下标处的最大值") | [Go](problems/maximum-value-at-a-given-index-in-a-bounded-array) | Medium | | 1801 | [Number of Orders in the Backlog](https://leetcode.com/problems/number-of-orders-in-the-backlog "积压订单中的订单总数") | [Go](problems/number-of-orders-in-the-backlog) | Medium | diff --git a/problems/132-pattern/README.md b/problems/132-pattern/README.md index 07d1b5481..8b2e5aca9 100644 --- a/problems/132-pattern/README.md +++ b/problems/132-pattern/README.md @@ -9,7 +9,7 @@ [Next>](../circular-array-loop "Circular Array Loop") -## [456. 132 Pattern (Medium)](https://leetcode.com/problems/132-pattern "132模式") +## [456. 132 Pattern (Medium)](https://leetcode.com/problems/132-pattern "132 模式")
Given an array of n
integers nums
, a 132 pattern is a subsequence of three integers nums[i]
, nums[j]
and nums[k]
such that i < j < k
and nums[i] < nums[k] < nums[j]
.
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
diff --git a/problems/ad-free-sessions/README.md b/problems/ad-free-sessions/README.md new file mode 100644 index 000000000..4bf3ad017 --- /dev/null +++ b/problems/ad-free-sessions/README.md @@ -0,0 +1,14 @@ + + + + + + + +[< Previous](../maximize-number-of-nice-divisors "Maximize Number of Nice Divisors") + +[Next>](../minimum-path-cost-in-a-hidden-grid "Minimum Path Cost in a Hidden Grid") + +## [1809. Ad-Free Sessions (Easy)](https://leetcode.com/problems/ad-free-sessions "") + + diff --git a/problems/ad-free-sessions/mysql_schemas.sql b/problems/ad-free-sessions/mysql_schemas.sql new file mode 100644 index 000000000..f430ed831 --- /dev/null +++ b/problems/ad-free-sessions/mysql_schemas.sql @@ -0,0 +1,12 @@ +Create table If Not Exists Playback(session_id int,customer_id int,start_time int,end_time int); +Create table If Not Exists Ads (ad_id int, customer_id int, timestamp int); +Truncate table Playback; +insert into Playback (session_id, customer_id, start_time, end_time) values ('1', '1', '1', '5'); +insert into Playback (session_id, customer_id, start_time, end_time) values ('2', '1', '15', '23'); +insert into Playback (session_id, customer_id, start_time, end_time) values ('3', '2', '10', '12'); +insert into Playback (session_id, customer_id, start_time, end_time) values ('4', '2', '17', '28'); +insert into Playback (session_id, customer_id, start_time, end_time) values ('5', '2', '2', '8'); +Truncate table Ads; +insert into Ads (ad_id, customer_id, timestamp) values ('1', '1', '5'); +insert into Ads (ad_id, customer_id, timestamp) values ('2', '2', '17'); +insert into Ads (ad_id, customer_id, timestamp) values ('3', '2', '20'); diff --git a/problems/add-strings/README.md b/problems/add-strings/README.md index f6cabe247..d48d79bcd 100644 --- a/problems/add-strings/README.md +++ b/problems/add-strings/README.md @@ -11,16 +11,41 @@ ## [415. Add Strings (Easy)](https://leetcode.com/problems/add-strings "字符串相加") -Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note: -
num1
and num2
is < 5100.num1
and num2
contains only digits 0-9
.num1
and num2
does not contain any leading zero.Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
Example 1:
+ ++Input: num1 = "11", num2 = "123" +Output: "134" ++ +
Example 2:
+ ++Input: num1 = "456", num2 = "77" +Output: "533" ++ +
Example 3:
+ ++Input: num1 = "0", num2 = "0" +Output: "0" ++ + +
Constraints:
+ +1 <= num1.length, num2.length <= 104
num1
and num2
consist of only digits.num1
and num2
don't have any leading zeros except for the zero itself.Follow up: Could you solve it without using any built-in BigInteger
library or converting the inputs to integer directly?
For a non-negative integer X
, the array-form of X
is an array of its digits in left to right order. For example, if X = 1231
, then the array form is [1,2,3,1]
.
The array-form of an integer num
is an array representing its digits in left to right order.
Given the array-form A
of a non-negative integer X
, return the array-form of the integer X+K
.
num = 1321
, the array form is [1,3,2,1]
.Given num
, the array-form of an integer, and an integer k
, return the array-form of the integer num + k
.
Example 1:
-Input: A = [1,2,0,0], K = 34 -Output: [1,2,3,4] -Explanation: 1200 + 34 = 1234 +Input: num = [1,2,0,0], k = 34 +Output: [1,2,3,4] +Explanation: 1200 + 34 = 1234-
Example 2:
-Input: A = [2,7,4], K = 181 -Output: [4,5,5] -Explanation: 274 + 181 = 455 +Input: num = [2,7,4], k = 181 +Output: [4,5,5] +Explanation: 274 + 181 = 455-
Example 3:
-Input: A = [2,1,5], K = 806 -Output: [1,0,2,1] -Explanation: 215 + 806 = 1021 +Input: num = [2,1,5], k = 806 +Output: [1,0,2,1] +Explanation: 215 + 806 = 1021-
Example 4:
-Input: A = [9,9,9,9,9,9,9,9,9,9], K = 1 -Output: [1,0,0,0,0,0,0,0,0,0,0] -Explanation: 9999999999 +たす 1 =わ 10000000000 +Input: num = [9,9,9,9,9,9,9,9,9,9], k = 1 +Output: [1,0,0,0,0,0,0,0,0,0,0] +Explanation: 9999999999 +たす 1 =わ 10000000000- -
Note:
- -1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
A.length > 1
, then A[0] != 0
Constraints:
+ +1 <= num.length <= 104
0 <= num[i] <= 9
num
does not contain any leading zeros except for the zero itself.1 <= k <= 104
n == ratings.length
1 <= n <= 2 * 104
1 <= ratings[i] <= 2 * 104
0 <= ratings[i] <= 2 * 104
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
+Given two integers n
and k
, return all possible combinations of k
numbers out of the range [1, n]
.
You may return the answer in any order.
diff --git a/problems/continuous-subarray-sum/README.md b/problems/continuous-subarray-sum/README.md index 55c6d5344..891529a26 100644 --- a/problems/continuous-subarray-sum/README.md +++ b/problems/continuous-subarray-sum/README.md @@ -11,32 +11,43 @@ ## [523. Continuous Subarray Sum (Medium)](https://leetcode.com/problems/continuous-subarray-sum "连续的子数组和") -Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer.
+Given an integer array nums
and an integer k
, return true
if nums
has a continuous subarray of size at least two whose elements sum up to a multiple of k
, or false
otherwise.
An integer x
is a multiple of k
if there exists an integer n
such that x = n * k
. 0
is always a multiple of k
.
Example 1:
+ ++Input: nums = [23,2,4,6,7], k = 6 +Output: true +Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. +-
Example 1:
+Example 2:
-Input: [23, 2, 4, 6, 7], k=6 -Output: True -Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6. +Input: nums = [23,2,6,4,7], k = 6 +Output: true +Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. +42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.-
Example 2:
+Example 3:
-Input: [23, 2, 6, 4, 7], k=6 -Output: True -Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. +Input: nums = [23,2,6,4,7], k = 13 +Output: false
Constraints:
1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= sum(nums[i]) <= 231 - 1
1 <= k <= 231 - 1
You are given an array nums
that consists of non-negative integers. Let us define rev(x)
as the reverse of the non-negative integer x
. For example, rev(123) = 321
, and rev(120) = 21
. A pair of indices (i, j)
is nice if it satisfies all of the following conditions:
0 <= i < j < nums.length
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7
.
Example 1:
+ ++Input: nums = [42,11,1,97] +Output: 2 +Explanation: The two pairs are: + - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121. + - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12. ++ +
Example 2:
+ ++Input: nums = [13,10,35,24,76] +Output: 4 ++ + +
Constraints:
+ +1 <= nums.length <= 105
0 <= nums[i] <= 109
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
+Given an integer n
, return the count of all numbers with unique digits, x
, where 0 <= x < 10n
.
Example:
+ +Example 1:
+ ++Input: n = 2 +Output: 91 +Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99 ++ +
Example 2:
-Input: 2
-Output: 91
-Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
- excluding 11,22,33,44,55,66,77,88,99
+Input: n = 0
+Output: 1
-Constraints:
diff --git a/problems/count-pairs-with-xor-in-a-range/README.md b/problems/count-pairs-with-xor-in-a-range/README.md index fa4fe3c9e..5e982118e 100644 --- a/problems/count-pairs-with-xor-in-a-range/README.md +++ b/problems/count-pairs-with-xor-in-a-range/README.md @@ -7,7 +7,7 @@ [< Previous](../maximum-value-at-a-given-index-in-a-bounded-array "Maximum Value at a Given Index in a Bounded Array") -Next> +[Next>](../implement-trie-ii-prefix-tree "Implement Trie II (Prefix Tree)") ## [1803. Count Pairs With XOR in a Range (Hard)](https://leetcode.com/problems/count-pairs-with-xor-in-a-range "统计异或值在范围内的数对有多少") diff --git a/problems/data-stream-as-disjoint-intervals/README.md b/problems/data-stream-as-disjoint-intervals/README.md index 3f9b567ab..85bd84e16 100644 --- a/problems/data-stream-as-disjoint-intervals/README.md +++ b/problems/data-stream-as-disjoint-intervals/README.md @@ -11,23 +11,50 @@ ## [352. Data Stream as Disjoint Intervals (Hard)](https://leetcode.com/problems/data-stream-as-disjoint-intervals "将数据流变为多个不相交区间") -Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.
+Given a data stream input of non-negative integers a1, a2, ..., an
, summarize the numbers seen so far as a list of disjoint intervals.
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
+Implement the SummaryRanges
class:
SummaryRanges()
Initializes the object with an empty stream.void addNum(int val)
Adds the integer val
to the stream.int[][] getIntervals()
Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]
.Example 1:
-[1, 1] -[1, 1], [3, 3] -[1, 1], [3, 3], [7, 7] -[1, 3], [7, 7] -[1, 3], [6, 7] +Input +["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"] +[[], [1], [], [3], [], [7], [], [2], [], [6], []] +Output +[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]] + +Explanation +SummaryRanges summaryRanges = new SummaryRanges(); +summaryRanges.addNum(1); // arr = [1] +summaryRanges.getIntervals(); // return [[1, 1]] +summaryRanges.addNum(3); // arr = [1, 3] +summaryRanges.getIntervals(); // return [[1, 1], [3, 3]] +summaryRanges.addNum(7); // arr = [1, 3, 7] +summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]] +summaryRanges.addNum(2); // arr = [1, 2, 3, 7] +summaryRanges.getIntervals(); // return [[1, 3], [7, 7]] +summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7] +summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]+
Constraints:
-Follow up:
+0 <= val <= 104
3 * 104
calls will be made to addNum
and getIntervals
.What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
+ +Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
### Related Topics [[Binary Search](../../tag/binary-search/README.md)] diff --git a/problems/design-twitter/README.md b/problems/design-twitter/README.md index c1ad18065..61390d7bd 100644 --- a/problems/design-twitter/README.md +++ b/problems/design-twitter/README.md @@ -11,45 +11,48 @@ ## [355. Design Twitter (Medium)](https://leetcode.com/problems/design-twitter "设计推特") -Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and is able to see the 10 most recent tweets in the user's news feed. Your design should support the following methods:
- --
Example: -
-Twitter twitter = new Twitter(); +Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the
-// User 1 posts a new tweet (id = 5). -twitter.postTweet(1, 5); +10
most recent tweets in the user's news feed.Implement the
-// User 1's news feed should return a list with 1 tweet id -> [5]. -twitter.getNewsFeed(1); +
Twitter()
Initializes your twitter object.void postTweet(int userId, int tweetId)
Composes a new tweet with ID tweetId
by the user userId
. Each call to this function will be made with a unique tweetId
.List<Integer> getNewsFeed(int userId)
Retrieves the 10
most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.void follow(int followerId, int followeeId)
The user with ID followerId
started following the user with ID followeeId
.void unfollow(int followerId, int followeeId)
The user with ID followerId
started unfollowing the user with ID followeeId
.Example 1:
-// User 2 posts a new tweet (id = 6). -twitter.postTweet(2, 6); ++Input +["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] +[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]] +Output +[null, null, [5], null, null, [6, 5], null, [5]] -// User 1's news feed should return a list with 2 tweet ids -> [6, 5]. -// Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. -twitter.getNewsFeed(1); +Explanation +Twitter twitter = new Twitter(); +twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5] +twitter.follow(1, 2); // User 1 follows user 2. +twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). +twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. +twitter.unfollow(1, 2); // User 1 unfollows user 2. +twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2. +-// User 1 unfollows user 2. -twitter.unfollow(1, 2); + +
Constraints:
-// User 1's news feed should return a list with 1 tweet id -> [5], -// since user 1 is no longer following user 2. -twitter.getNewsFeed(1); - - +1 <= userId, followerId, followeeId <= 500
0 <= tweetId <= 104
3 * 104
calls will be made to postTweet
, getNewsFeed
, follow
, and unfollow
.An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
+Implement the UndergroundSystem
class:
void checkIn(int id, string stationName, int t)
id
, gets in the station stationName
at time t
.id
, checks in at the station stationName
at time t
.void checkOut(int id, string stationName, int t)
id
, gets out from the station stationName
at time t
.id
, checks out from the station stationName
at time t
.double getAverageTime(string startStation, string endStation)
startStation
and the endStation
.startStation
to endStation
that happened directly.getAverageTime
is always valid.startStation
to endStation
.startStation
to endStation
that happened directly, meaning a check in at startStation
followed by a check out from endStation
.startStation
to endStation
may be different from the time it takes to travel from endStation
to startStation
.startStation
to endStation
before getAverageTime
is called.You can assume all calls to checkIn
and checkOut
methods are consistent. If a customer gets in at time t1 at some station, they get out at time t2 with t2 > t1. All events happen in chronological order.
You may assume all calls to the checkIn
and checkOut
methods are consistent. If a customer checks in at time t1
then checks out at time t2
, then t1 < t2
. All events happen in chronological order.
Example 1:
@@ -52,15 +55,15 @@ UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(45, "Leyton", 3); undergroundSystem.checkIn(32, "Paradise", 8); undergroundSystem.checkIn(27, "Leyton", 10); -undergroundSystem.checkOut(45, "Waterloo", 15); -undergroundSystem.checkOut(27, "Waterloo", 20); -undergroundSystem.checkOut(32, "Cambridge", 22); -undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. There was only one travel from "Paradise" (at time 8) to "Cambridge" (at time 22) -undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. There were two travels from "Leyton" to "Waterloo", a customer with id=45 from time=3 to time=15 and a customer with id=27 from time=10 to time=20. So the average time is ( (15-3) + (20-10) ) / 2 = 11.00000 +undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12 +undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10 +undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14 +undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14 +undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11 undergroundSystem.checkIn(10, "Leyton", 24); -undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 -undergroundSystem.checkOut(10, "Waterloo", 38); -undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000 +undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000 +undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14 +undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12Example 2:
@@ -76,25 +79,25 @@ undergroundSystem.getAverageTime("Leyton", "Waterloo"); &nbs Explanation UndergroundSystem undergroundSystem = new UndergroundSystem(); undergroundSystem.checkIn(10, "Leyton", 3); -undergroundSystem.checkOut(10, "Paradise", 8); -undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000 +undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5 +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5 undergroundSystem.checkIn(5, "Leyton", 10); -undergroundSystem.checkOut(5, "Paradise", 16); -undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000 +undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6 +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5 undergroundSystem.checkIn(2, "Leyton", 21); -undergroundSystem.checkOut(2, "Paradise", 30); -undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667 +undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9 +undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667Constraints:
20000
operations.1 <= id, t <= 106
1 <= stationName.length <= 10
10-5
of the actual value will be accepted as correct.1 <= stationName.length, startStation.length, endStation.length <= 10
2 * 104
calls in total to checkIn
, checkOut
, and getAverageTime
.10-5
of the actual value will be accepted.You are given coordinates
, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return true
if the square is white, and false
if the square is black.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
+ + +Example 1:
+ ++Input: coordinates = "a1" +Output: false +Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false. ++ +
Example 2:
+ ++Input: coordinates = "h3" +Output: true +Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true. ++ +
Example 3:
+ ++Input: coordinates = "c7" +Output: false ++ + +
Constraints:
+ +coordinates.length == 2
'a' <= coordinates[0] <= 'h'
'1' <= coordinates[1] <= '8'
Given a string S
that only contains "I" (increase) or "D" (decrease), let N = S.length
.
Return any permutation A
of [0, 1, ..., N]
such that for all i = 0, ..., N-1
:
A permutation perm
of n + 1
integers of all the integers in the range [0, n]
can be represented as a string s
of length n
where:
S[i] == "I"
, then A[i] < A[i+1]
S[i] == "D"
, then A[i] > A[i+1]
s[i] == 'I'
if perm[i] < perm[i + 1]
, ands[i] == 'D'
if perm[i] > perm[i + 1]
.Given a string s
, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.
Example 1:
- --Input: "IDID" -Output: [0,4,1,3,2] -- -
Example 2:
- --Input: "III" -Output: [0,1,2,3] +Input: s = "IDID" +Output: [0,4,1,3,2] +Example 2:
+Input: s = "III" +Output: [0,1,2,3] +Example 3:
+Input: s = "DDI" +Output: [3,2,0,1]- ---Example 3:
- --Input: "DDI" -Output: [3,2,0,1]-
Constraints:
-Note:
- -1 <= S.length <= 10000
S
only contains characters "I"
or "D"
.1 <= s.length <= 105
s[i]
is either 'I'
or 'D'
.Constraints:
0 <= s.length, t.length <= 1000
1 <= s.length, t.length <= 1000
s
and t
consist of English letters.Alice and Bob take turns playing a game, with Alice starting first.
-Initially, there is a number N
on the chalkboard. On each player's turn, that player makes a move consisting of:
Initially, there is a number n
on the chalkboard. On each player's turn, that player makes a move consisting of:
x
with 0 < x < N
and N % x == 0
.N
on the chalkboard with N - x
.x
with 0 < x < n
and n % x == 0
.n
on the chalkboard with n - x
.Also, if a player cannot make a move, they lose the game.
-Return True
if and only if Alice wins the game, assuming both players play optimally.
Return true
if and only if Alice wins the game, assuming both players play optimally.
Example 1:
-Input: 2 -Output: true +Input: n = 2 +Output: true Explanation: Alice chooses 1, and Bob has no more moves.-
Example 2:
-Input: 3 -Output: false +Input: n = 3 +Output: false Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.+
Constraints:
-Note:
- -1 <= N <= 1000
1 <= n <= 1000
-There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.
+You have a list arr
of all integers in the range [1, n]
sorted in a strictly increasing order. Apply the following algorithm on arr
:
Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.
+We keep repeating the steps again, alternating left to right and right to left, until a single number remains.
+Given the integer n
, return the last number that remains in arr
.
Find the last number that remains starting with a list of length n.
+ +Example 1:
-Example:
-Input: -n = 9, -1 2 3 4 5 6 7 8 9 -2 4 6 8 -2 6 -6 - -Output: -6 +Input: n = 9 +Output: 6 +Explanation: +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +arr = [2, 4, 6, 8] +arr = [2, 6] +arr = [6]- + +
Example 2:
+ ++Input: n = 1 +Output: 1 ++ + +
Constraints:
+ +1 <= n <= 109
You are given a string s
that contains some bracket pairs, with each pair containing a non-empty key.
"(name)is(age)yearsold"
, there are two bracket pairs that contain the keys "name"
and "age"
.You know the values of a wide range of keys. This is represented by a 2D string array knowledge
where each knowledge[i] = [keyi, valuei]
indicates that key keyi
has a value of valuei
.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi
, you will:
keyi
and the bracket pair with the key's corresponding valuei
.keyi
and the bracket pair with a question mark "?"
(without the quotation marks).Each key will appear at most once in your knowledge
. There will not be any nested brackets in s
.
Return the resulting string after evaluating all of the bracket pairs.
+ + +Example 1:
+ ++Input: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]] +Output: "bobistwoyearsold" +Explanation: +The key "name" has a value of "bob", so replace "(name)" with "bob". +The key "age" has a value of "two", so replace "(age)" with "two". ++ +
Example 2:
+ ++Input: s = "hi(name)", knowledge = [["a","b"]] +Output: "hi?" +Explanation: As you do not know the value of the key "name", replace "(name)" with "?". ++ +
Example 3:
+ ++Input: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]] +Output: "yesyesyesaaa" +Explanation: The same key can appear multiple times. +The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes". +Notice that the "a"s not in a bracket pair are not evaluated. ++ +
Example 4:
+ ++Input: s = "(a)(b)", knowledge = [["a","b"],["b","a"]] +Output: "ba"+ + +
Constraints:
+ +1 <= s.length <= 105
0 <= knowledge.length <= 105
knowledge[i].length == 2
1 <= keyi.length, valuei.length <= 10
s
consists of lowercase English letters and round brackets '('
and ')'
.'('
in s
will have a corresponding close bracket ')'
.s
will be non-empty.s
.keyi
and valuei
consist of lowercase English letters.keyi
in knowledge
is unique.Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
- -Find all the elements of [1, n] inclusive that do not appear in this array.
- -Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
+Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
Example 1:
+Input: nums = [4,3,2,7,8,2,3,1] +Output: [5,6] +
Example 2:
+Input: nums = [1,1] +Output: [2] ++ +
Constraints:
-Example: -
-Input: -[4,3,2,7,8,2,3,1] +
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n)
runtime? You may assume the returned list does not count as extra space.
Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.
+Given a list paths
of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have exactly the same content.
+A group of duplicate files consists of at least two files that have the same content.
-A single directory info string in the input list has the following format:
+A single directory info string in the input list has the following format:
-"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n files (f1.txt
, f2.txt
... fn.txt
with content f1_content
, f2_content
... fn_content
, respectively) in directory root/d1/d2/.../dm
. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
It means there are n
files (f1.txt, f2.txt ... fn.txt)
with content (f1_content, f2_content ... fn_content)
respectively in the directory "root/d1/d2/.../dm"
. Note that n >= 1
and m >= 0
. If m = 0
, it means the directory is just the root directory.
The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
+The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
-"directory_path/file_name.txt"
"directory_path/file_name.txt"
Example 1:
- --Input: -["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"] -Output: -[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] + +Example 1:
+Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"] +Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]] +Example 2:
+Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"] +Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]- +Constraints:
-Note:
- --
+- No order is required for the final output.
-- You may assume the directory name, file name and file content only has letters and digits, and the length of file content is in the range of [1,50].
-- The number of files given is in the range of [1,20000].
++
- +
1 <= paths.length <= 2 * 104
- +
1 <= paths[i].length <= 3000
- +
1 <= sum(paths[i].length) <= 5 * 105
paths[i]
consist of English letters, digits,'/'
,'.'
,'('
,')'
, and' '
.- You may assume no files or directories share the same name in the same directory.
-- You may assume each given directory info represents a unique directory. Directory path and file info are separated by a single blank space.
-
Follow up:
-You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
+You are given two integer arrays nums1
and nums2
sorted in ascending order and an integer k
.
Define a pair (u,v) which consists of one element from the first array and one element from the second array.
+Define a pair (u, v)
which consists of one element from the first array and one element from the second array.
Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
+Return the k
pairs (u1, v1), (u2, v2), ..., (uk, vk)
with the smallest sums.
Example 1:
-Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 -Output: [[1,2],[1,4],[1,6]] -Explanation: The first 3 pairs are returned from the sequence: - [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]+Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3 +Output: [[1,2],[1,4],[1,6]] +Explanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6] +
Example 2:
-Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
-Output: [1,1],[1,1]
-Explanation: The first 2 pairs are returned from the sequence:
- [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
+Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
+Output: [[1,1],[1,1]]
+Explanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
+
Example 3:
-Input: nums1 = [1,2], nums2 = [3], k = 3
-Output: [1,3],[2,3]
-Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
+Input: nums1 = [1,2], nums2 = [3], k = 3
+Output: [[1,3],[2,3]]
+Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]
+
+Constraints:
+ +1 <= nums1.length, nums2.length <= 104
-109 <= nums1[i], nums2[i] <= 109
nums1
and nums2
both are sorted in ascending order.1 <= k <= 1000
You are given the logs for users' actions on LeetCode, and an integer k
. The logs are represented by a 2D integer array logs
where each logs[i] = [IDi, timei]
indicates that the user with IDi
performed an action at the minute timei
.
Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.
+ +The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.
+ +You are to calculate a 1-indexed array answer
of size k
such that, for each j
(1 <= j <= k
), answer[j]
is the number of users whose UAM equals j
.
Return the array answer
as described above.
Example 1:
+ ++Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5 +Output: [0,2,0,0,0] +Explanation: +The user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once). +The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. +Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0. ++ +
Example 2:
+ ++Input: logs = [[1,1],[2,2],[2,3]], k = 4 +Output: [1,1,0,0] +Explanation: +The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1. +The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2. +There is one user with a UAM of 1 and one with a UAM of 2. +Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0. ++ + +
Constraints:
+ +1 <= logs.length <= 104
0 <= IDi <= 109
1 <= timei <= 105
k
is in the range [The maximum UAM for a user, 105]
.Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
+Given a string s
, return the first non-repeating character in it and return its index. If it does not exist, return -1
.
Examples:
- --s = "leetcode" -return 0. - -s = "loveleetcode" -return 2. + +Example 1:
+Input: s = "leetcode" +Output: 0 +Example 2:
+Input: s = "loveleetcode" +Output: 2 +Example 3:
+Input: s = "aabb" +Output: -1- +Constraints:
-Note: You may assume the string contains only lowercase English letters.
+
1 <= s.length <= 105
s
consists of only lowercase English letters.Given a nested list of integers, implement an iterator to flatten it.
+You are given a nested list of integers nestedList
. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
+Implement the NestedIterator
class:
NestedIterator(List<NestedInteger> nestedList)
Initializes the iterator with the nested list nestedList
.int next()
Returns the next integer in the nested list.boolean hasNext()
Returns true
if there are still some integers in the nested list and false
otherwise.Example 1:
-
-Input: [[1,1],2,[1,1]]
-Output: [1,1,2,1,1]
-Explanation: By calling next repeatedly until hasNext returns false,
- the order of elements returned by next should be: [1,1,2,1,1]
.
+Input: nestedList = [[1,1],2,[1,1]]
+Output: [1,1,2,1,1]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
+
-Example 2:
-Input: [1,[4,[6]]]
-Output: [1,4,6]
-Explanation: By calling next repeatedly until hasNext returns false,
- the order of elements returned by next should be: [1,4,6]
.
+Input: nestedList = [1,[4,[6]]]
+Output: [1,4,6]
+Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
-Constraints:
+ +1 <= nestedList.length <= 500
[-106, 106]
.This problem is an interactive problem new to the LeetCode platform.
+This is an interactive problem.
-We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.
+You are given an array of unique strings wordlist
where wordlist[i]
is 6
letters long, and one word in this list is chosen as secret
.
You may call master.guess(word)
to guess a word. The guessed word should have type string
and must be from the original list with 6 lowercase letters.
You may call Master.guess(word)
to guess a word. The guessed word should have type string
and must be from the original list with 6
lowercase letters.
This function returns an integer
type, representing the number of exact matches (value and position) of your guess to the secret word. Also, if your guess is not in the given wordlist, it will return -1
instead.
This function returns an integer
type, representing the number of exact matches (value and position) of your guess to the secret
word. Also, if your guess is not in the given wordlist, it will return -1
instead.
For each test case, you have 10 guesses to guess the word. At the end of any number of calls, if you have made 10 or less calls to master.guess
and at least one of these guesses was the secret, you pass the testcase.
For each test case, you have exactly 10
guesses to guess the word. At the end of any number of calls, if you have made 10
or fewer calls to Master.guess
and at least one of these guesses was secret
, then you pass the test case.
Besides the example test case below, there will be 5 additional test cases, each with 100 words in the word list. The letters of each word in those testcases were chosen independently at random from 'a'
to 'z'
, such that every word in the given word lists is unique.
Example 1:
-Example 1: -Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"] - +Input: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"], numguesses = 10 +Output: You guessed the secret word correctly. Explanation: +master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. +master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. +master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. +master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. +master.guess("abcczz") returns 4, because "abcczz" has 4 matches. +We made 5 calls to master.guess and one of them was the secret, so we pass the test case. +-
master.guess("aaaaaa")
returns -1, because "aaaaaa"
is not in wordlist.
-master.guess("acckzz")
returns 6, because "acckzz"
is secret and has all 6 matches.
-master.guess("ccbazz")
returns 3, because "ccbazz"
has 3 matches.
-master.guess("eiowzz")
returns 2, because "eiowzz"
has 2 matches.
-master.guess("abcczz")
returns 4, because "abcczz"
has 4 matches.
+Example 2:
-We made 5 calls to master.guess and one of them was the secret, so we pass the test case. ++Input: secret = "hamada", wordlist = ["hamada","khaled"], numguesses = 10 +Output: You guessed the secret word correctly.-
Note: Any solutions that attempt to circumvent the judge will result in disqualification.
+ +Constraints:
+ +1 <= wordlist.length <= 100
wordlist[i].length == 6
wordlist[i]
consist of lowercase English letters.wordlist
are unique.secret
exists in wordlist
.numguesses == 10
Trie (we pronounce "try") or prefix tree is a tree data structure used to retrieve a key in a strings dataset. There are various applications of this very efficient data structure, such as autocomplete and spellchecker.
+A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()
initializes the trie object.void insert(String word)
inserts the string word
to the trie.boolean search(String word)
returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.boolean startsWith(String prefix)
returns true
if there is a previously inserted string word
that has the prefix prefix
, and false
otherwise.Trie()
Initializes the trie object.void insert(String word)
Inserts the string word
into the trie.boolean search(String word)
Returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.boolean startsWith(String prefix)
Returns true
if there is a previously inserted string word
that has the prefix prefix
, and false
otherwise.1 <= word.length, prefix.length <= 2000
word
and prefix
consist of lowercase English letters.3 * 104
calls will be made to insert
, search
, and startsWith
.word
and prefix
consist only of lowercase English letters.3 * 104
calls in total will be made to insert
, search
, and startsWith
.Given strings s1
, s2
, and s3
, find whether s3
is formed by an interleaving of s1
and s2
.
0 <= s1.length, s2.length <= 100
0 <= s3.length <= 200
s1
, s2
, and s3
consist of lower-case English letters.s1
, s2
, and s3
consist of lowercase English letters.Follow up: Could you solve it using only O(s2.length)
additional memory space?
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane and an integer k
, return the k
closest points to the origin (0, 0)
.
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane and an integer k
, return the k
closest points to the origin (0, 0)
.
The distance between two points on the X-Y plane is the Euclidean distance (i.e, √(x1 - x2)2 + (y1 - y2)2
).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2
).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
diff --git a/problems/kth-smallest-element-in-a-sorted-matrix/README.md b/problems/kth-smallest-element-in-a-sorted-matrix/README.md index 1f2780795..a057f4b6e 100644 --- a/problems/kth-smallest-element-in-a-sorted-matrix/README.md +++ b/problems/kth-smallest-element-in-a-sorted-matrix/README.md @@ -38,7 +38,7 @@n == matrix.length
n == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= -109
-109 <= matrix[i][j] <= 109
matrix
are guaranteed to be sorted in non-degreasing order.1 <= k <= n2
Multiple instructions will lead Bob to destination
. For example, if destination
is (2, 3)
, both "HHHVV"
and "HVHVH"
are valid instructions.
However, Bob is very picky. Bob has a lucky number k
, and he wants the kth
lexicographically smallest instructions that will lead him to destination
. k
is 1-indexed.
Given an integer array destination
and an integer k
, return the kth
lexicographically smallest instructions that will take Bob to destination
.
Given an integer array destination
and an integer k
, return the kth
lexicographically smallest instructions that will take Bob to destination
.
Example 1:
diff --git a/problems/lexicographical-numbers/README.md b/problems/lexicographical-numbers/README.md index 202709cbe..8d96fd73a 100644 --- a/problems/lexicographical-numbers/README.md +++ b/problems/lexicographical-numbers/README.md @@ -11,8 +11,22 @@ ## [386. Lexicographical Numbers (Medium)](https://leetcode.com/problems/lexicographical-numbers "字典序排数") -Given an integer n, return 1 - n in lexicographical order.
+Given an integer n
, return all the numbers in the range [1, n]
sorted in lexicographical order.
For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
+ +Example 1:
+Input: n = 13 +Output: [1,10,11,12,13,2,3,4,5,6,7,8,9] +
Example 2:
+Input: n = 2 +Output: [1,2] ++ +
Constraints:
-Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
+1 <= n <= 5 * 104
Follow up: Could you optimize your solution to use O(n)
runtime and O(1)
space?
Given a binary tree root
, a ZigZag path for a binary tree is defined as follow:
You are given the root
of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
-Return the longest ZigZag path contained in that tree.
+Return the longest ZigZag path contained in that tree.
Example 1:
- - - +Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1] Output: 3 @@ -36,9 +36,7 @@
Example 2:
- - - +Input: root = [1,1,1,null,1,null,null,1,1,null,1] Output: 4 @@ -56,8 +54,8 @@Constraints:
50000
nodes..[1, 100]
.[1, 5 * 104]
.1 <= Node.val <= 100
m * n
matrix mat
and an integer K
, return a matrix answer
where each answer[i][j]
is the sum of all elements mat[r][c]
for i - K <= r <= i + K, j - K <= c <= j + K
, and (r, c)
is a valid position in the matrix.
+Given a m x n
matrix mat
and an integer k
, return a matrix answer
where each answer[i][j]
is the sum of all elements mat[r][c]
for:
i - k <= r <= i + k,
j - k <= c <= j + k
, and(r, c)
is a valid position in the matrix.Example 1:
-Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1 +Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
-Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2 +Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 Output: [[45,45,45],[45,45,45],[45,45,45]]@@ -33,7 +40,7 @@ Given a
m * n
matrix mat
and an integer m == mat.length
n == mat[i].length
1 <= m, n, K <= 100
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100
m == matrix.length
n == matrix[i].length
1 <= m, n <= 3000
1 <= m * n <= 5 * 104
1 <= m, n <= 100
-100 <= matrix[i][j] <= 100
-105 <= k <= 105
You are given a positive integer primeFactors
. You are asked to construct a positive integer n
that satisfies the following conditions:
n
(not necessarily distinct) is at most primeFactors
.n
is maximized. Note that a divisor of n
is nice if it is divisible by every prime factor of n
. For example, if n = 12
, then its prime factors are [2,2,3]
, then 6
and 12
are nice divisors, while 3
and 4
are not.Return the number of nice divisors of n
. Since that number can be too large, return it modulo 109 + 7
.
Note that a prime number is a natural number greater than 1
that is not a product of two smaller natural numbers. The prime factors of a number n
is a list of prime numbers such that their product equals n
.
Example 1:
+ ++Input: primeFactors = 5 +Output: 6 +Explanation: 200 is a valid value of n. +It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200]. +There is not other value of n that has at most 5 prime factors and more nice divisors. ++ +
Example 2:
+ ++Input: primeFactors = 8 +Output: 18 ++ + +
Constraints:
+ +1 <= primeFactors <= 109
There is a donuts shop that bakes donuts in batches of batchSize
. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize
and an integer array groups
, where groups[i]
denotes that there is a group of groups[i]
customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
+ +You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
+ + +Example 1:
+ ++Input: batchSize = 3, groups = [1,2,3,4,5,6] +Output: 4 +Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy. ++ +
Example 2:
+ ++Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6] +Output: 4 ++ + +
Constraints:
+ +1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 109
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums
is guaranteed to fit in a 32-bit integer.You are given three positive integers n
, index
and maxSum
. You want to construct an array nums
(0-indexed) that satisfies the following conditions:
You are given three positive integers: n
, index
, and maxSum
. You want to construct an array nums
(0-indexed)that satisfies the following conditions:
nums.length == n
nums[index]
is maximized.Return nums[index]
of the constructed array.
Return nums[index]
of the constructed array.
Note that abs(x)
equals x
if x >= 0
, and -x
otherwise.
Input: n = 4, index = 2, maxSum = 6 Output: 2 -Explanation: The arrays [1,1,2,1] and [1,2,2,1] satisfy all the conditions. There are no other valid arrays with a larger value at the given index. +Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions. +There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
Example 2:
diff --git a/problems/mini-parser/README.md b/problems/mini-parser/README.md index 711e765b7..2ab07f484 100644 --- a/problems/mini-parser/README.md +++ b/problems/mini-parser/README.md @@ -11,45 +11,40 @@ ## [385. Mini Parser (Medium)](https://leetcode.com/problems/mini-parser "迷你语法分析器") -Given a nested list of integers represented as a string, implement a parser to deserialize it.
+Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger
.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
- -Note: You may assume that the string is well-formed:
- -0-9
, [
, -
,
, ]
.Each element is either an integer or a list whose elements may also be integers or other lists.
- -Example 1:
+Example 1:
-Given s = "324", - -You should return a NestedInteger object which contains a single integer 324. +Input: s = "324" +Output: 324 +Explanation: You should return a NestedInteger object which contains a single integer 324.- - -
Example 2:
+Example 2:
-Given s = "[123,[456,[789]]]", - -Return a NestedInteger object containing a nested list with 2 elements: - +Input: s = "[123,[456,[789]]]" +Output: [123,[456,[789]]] +Explanation: Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: - a. An integer containing value 789. + a. An integer containing value 789+
Constraints:
+ +1 <= s.length <= 5 * 104
s
consists of digits, square brackets "[]"
, negative sign '-'
, and commas ','
.s
is the serialization of valid NestedInteger
.You are given two positive integer arrays nums1
and nums2
, both of length n
.
The absolute sum difference of arrays nums1
and nums2
is defined as the sum of |nums1[i] - nums2[i]|
for each 0 <= i < n
(0-indexed).
You can replace at most one element of nums1
with any other element in nums1
to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most oneelement in the array nums1
. Since the answer may be large, return it modulo 109 + 7
.
|x|
is defined as:
x
if x >= 0
, or-x
if x < 0
.Example 1:
+ +
+Input: nums1 = [1,7,5], nums2 = [2,3,5]
+Output: 3
+Explanation: There are two possible optimal solutions:
+- Replace the second element with the first: [1,7,5] => [1,1,5], or
+- Replace the second element with the third: [1,7,5] => [1,5,5].
+Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| =
3.
+
+
+Example 2:
+ ++Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10] +Output: 0 +Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an +absolute sum difference of 0. ++ +
Example 3:
+ +
+Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
+Output: 20
+Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
+This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
+
+
+
+Constraints:
+ +n == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105
You are given two groups of points where the first group has size1
points, the second group has size2
points, and size1 >= size2
.
You are given two groups of points where the first group has size1
points, the second group has size2
points, and size1 >= size2
.
The cost
of the connection between any two points are given in an size1 x size2
matrix where cost[i][j]
is the cost of connecting point i
of the first group and point j
of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
The cost
of the connection between any two points are given in an size1 x size2
matrix where cost[i][j]
is the cost of connecting point i
of the first group and point j
of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return the minimum cost it takes to connect the two groups.
+Return the minimum cost it takes to connect the two groups.
Example 1:
@@ -54,10 +54,10 @@ Note that there are multiple points connected to point 2 in the first group andConstraints:
size1 == cost.length
size2 == cost[i].length
1 <= size1, size2 <= 12
size1 >= size2
size1 == cost.length
size2 == cost[i].length
1 <= size1, size2 <= 12
size1 >= size2
0 <= cost[i][j] <= 100
You are given an even integer n
. You initially have a permutation perm
of size n
where perm[i] == i
(0-indexed).
In one operation, you will create a new array arr
, and for each i
:
i % 2 == 0
, then arr[i] = perm[i / 2]
.i % 2 == 1
, then arr[i] = perm[n / 2 + (i - 1) / 2]
.You will then assign arr
to perm
.
Return the minimum non-zero number of operations you need to perform on perm
to return the permutation to its initial value.
Example 1:
+ ++Input: n = 2 +Output: 1 +Explanation: perm = [0,1] initially. +After the 1st operation, perm = [0,1] +So it takes only 1 operation. ++ +
Example 2:
+ ++Input: n = 4 +Output: 2 +Explanation: perm = [0,1,2,3] initially. +After the 1st operation, perm = [0,2,1,3] +After the 2nd operation, perm = [0,1,2,3] +So it takes only 2 operations. ++ +
Example 3:
+ ++Input: n = 6 +Output: 4 ++ + +
Constraints:
+ +2 <= n <= 1000
n
is even.-Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number. -
+Given a circular integer array nums
(i.e., the next element of nums[nums.length - 1]
is nums[0]
), return the next greater number for every element in nums
.
The next greater number of a number x
is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1
for this number.
Example 1:
-Example 1:
-Input: [1,2,1] -Output: [2,-1,2] -Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number; The second 1's next greater number needs to search circularly, which is also 2. +Input: nums = [1,2,1] +Output: [2,-1,2] +Explanation: The first 1's next greater number is 2; +The number 2 can't find next greater number. +The second 1's next greater number needs to search circularly, which is also 2.- -
Note: -The length of given array won't exceed 10000. -
+Example 2:
+ ++Input: nums = [1,2,3,4,3] +Output: [2,3,4,-1,4] ++ + +
Constraints:
+ +1 <= nums.length <= 104
-109 <= nums[i] <= 109
You are given a string word
that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34"
will become " 123 34 8 34"
. Notice that you are left with some integers that are separated by at least one space: "123"
, "34"
, "8"
, and "34"
.
Return the number of different integers after performing the replacement operations on word
.
Two integers are considered different if their decimal representations without any leading zeros are different.
+ + +Example 1:
+ ++Input: word = "a123bc34d8ef34" +Output: 3 +Explanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once. ++ +
Example 2:
+ ++Input: word = "leet1234code234" +Output: 2 ++ +
Example 3:
+ ++Input: word = "a1b01c001" +Output: 1 +Explanation: The three integers "1", "01", and "001" all represent the same integer because +the leading zeros are ignored when comparing their decimal values. ++ + +
Constraints:
+ +1 <= word.length <= 1000
word
consists of digits and lowercase English letters.You are given an array nums
that consists of positive integers.
The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.
+ +[4,6,16]
is 2
.A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
+ +[2,5,10]
is a subsequence of [1,2,1,2,4,1,5,10]
.Return the number of different GCDs among all non-empty subsequences of nums
.
Example 1:
+ ++Input: nums = [6,10,3] +Output: 5 +Explanation: The figure shows all the non-empty subsequences and their GCDs. +The different GCDs are 6, 10, 3, 2, and 1. ++ +
Example 2:
+ ++Input: nums = [5,15,40,5,6] +Output: 7 ++ + +
Constraints:
+ +1 <= nums.length <= 105
1 <= nums[i] <= 2 * 105
Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
You are given an m x n
integer matrix heights
representing the height of each unit cell in a continent. The Pacific ocean touches the continent's left and top edges, and the Atlantic ocean touches the continent's right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
+Water can only flow in four directions: up, down, left, and right. Water flows from a cell to an adjacent one with an equal or lower height.
-Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
- -Note:
- -Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.
- -Example:
- +Example 1:
+-Given the following 5x5 matrix: - - Pacific ~ ~ ~ ~ ~ - ~ 1 2 2 3 (5) * - ~ 3 2 3 (4) (4) * - ~ 2 4 (5) 3 1 * - ~ (6) (7) 1 4 5 * - ~ (5) 1 1 2 4 * - * * * * * Atlantic +Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]] +Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]] +-Return: +
Example 2:
-[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix). ++Input: heights = [[2,1],[1,2]] +Output: [[0,0],[0,1],[1,0],[1,1]]+
Constraints:
+ +m == heights.length
n == heights[i].length
1 <= m, n <= 200
1 <= heights[i][j] <= 105
In a gold mine grid
of size m * n
, each cell in this mine has an integer representing the amount of gold in that cell, 0
if it is empty.
In a gold mine grid
of size m x n
, each cell in this mine has an integer representing the amount of gold in that cell, 0
if it is empty.
Return the maximum amount of gold you can collect under the conditions:
+Return the maximum amount of gold you can collect under the conditions:
0
gold.0
gold.Constraints:
1 <= grid.length, grid[i].length <= 15
m == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
+Given an array rectangles
where rectangles[i] = [xi, yi, ai, bi]
represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi)
and the top-right point of it is (ai, bi)
.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
- - - -Example 1:
+Return true
if all the rectangles together form an exact cover of a rectangular region.
Example 1:
+-rectangles = [ - [1,1,3,3], - [3,1,4,2], - [3,2,4,4], - [1,3,2,4], - [2,3,3,4] -] - -Return true. All 5 rectangles together form an exact cover of a rectangular region. +Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] +Output: true +Explanation: All 5 rectangles together form an exact cover of a rectangular region.- - - - - - -
Example 2:
- +Example 2:
+-rectangles = [ - [1,1,2,3], - [1,3,2,4], - [3,1,4,2], - [3,2,4,4] -] - -Return false. Because there is a gap between the two rectangular regions. +Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] +Output: false +Explanation: Because there is a gap between the two rectangular regions.- - - - - - -
Example 3:
- +Example 3:
+-rectangles = [ - [1,1,3,3], - [3,1,4,2], - [1,3,2,4], - [3,2,4,4] -] - -Return false. Because there is a gap in the top center. +Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]] +Output: false +Explanation: Because there is a gap in the top center.- - - - - - -
Example 4:
- +Example 4:
+-rectangles = [ - [1,1,3,3], - [3,1,4,2], - [1,3,2,4], - [2,2,4,4] -] - -Return false. Because two of the rectangles overlap with each other. +Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] +Output: false +Explanation: Because two of the rectangles overlap with each other.+
Constraints:
+ +1 <= rectangles.length <= 2 * 104
rectangles[i].length == 4
-105 <= xi, yi, ai, bi <= 105
Implement pow(x, n), which calculates x raised to the power n (i.e. xn).
+Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
Example 1:
diff --git a/problems/random-pick-index/README.md b/problems/random-pick-index/README.md index 377cef862..0ca6f4c30 100644 --- a/problems/random-pick-index/README.md +++ b/problems/random-pick-index/README.md @@ -11,23 +11,41 @@ ## [398. Random Pick Index (Medium)](https://leetcode.com/problems/random-pick-index "随机数索引") -Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
+Given an integer array nums
with possible duplicates, randomly output the index of a given target
number. You can assume that the given target number must exist in the array.
Note:
-The array size can be very large. Solution that uses too much extra space will not pass the judge.
Implement the Solution
class:
Example:
+Solution(int[] nums)
Initializes the object with the array nums
.int pick(int target)
Picks a random index i
from nums
where nums[i] == target
. If there are multiple valid i's, then each index should have an equal probability of returning.Example 1:
-int[] nums = new int[] {1,2,3,3,3}; -Solution solution = new Solution(nums); +Input +["Solution", "pick", "pick", "pick"] +[[[1, 2, 3, 3, 3]], [3], [1], [3]] +Output +[null, 4, 0, 2] + +Explanation +Solution solution = new Solution([1, 2, 3, 3, 3]); +solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. +solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. +solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. +-// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. -solution.pick(3); + +
Constraints:
-// pick(1) should return 0. Since in the array only nums[0] is equal to 1. -solution.pick(1); - +1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
target
is an integer from nums
.104
calls will be made to pick
.Given a non-empty string containing an out-of-order English representation of digits 0-9
, output the digits in ascending order.
Note:
-
Example 1:
-
-Input: "owoztneoer" - -Output: "012" -- - -
Example 2:
-
-Input: "fviefuro" - -Output: "45" +Given a string
+ + +s
containing an out-of-order English representation of digits0-9
, return the digits in ascending order.Example 1:
+Input: s = "owoztneoer" +Output: "012" +Example 2:
+Input: s = "fviefuro" +Output: "45"- + +Constraints:
+ +
1 <= s.length <= 105
s[i]
is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]
.s
is guaranteed to be valid.Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
diff --git a/problems/reordered-power-of-2/README.md b/problems/reordered-power-of-2/README.md index b3ff34da4..dcc0530d1 100644 --- a/problems/reordered-power-of-2/README.md +++ b/problems/reordered-power-of-2/README.md @@ -11,67 +11,52 @@ ## [869. Reordered Power of 2 (Medium)](https://leetcode.com/problems/reordered-power-of-2 "重新排序得到 2 的幂") -Starting with a positive integer N
, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
You are given an integer n
. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true
if and only if we can do this in a way such that the resulting number is a power of 2.
Return true
if and only if we can do this so that the resulting number is a power of two.
Example 1:
-Input: 1 -Output: true +Input: n = 1 +Output: true-
Example 2:
-Input: 10 -Output: false +Input: n = 10 +Output: false-
Example 3:
-Input: 16 -Output: true +Input: n = 16 +Output: true-
Example 4:
-Input: 24 -Output: false +Input: n = 24 +Output: false-
Example 5:
-Input: 46 -Output: true +Input: n = 46 +Output: true+
Constraints:
-Note:
- -1 <= N <= 10^9
1 <= n <= 109
Write a function that takes a string as input and reverse only the vowels of a string.
+Given a string s
, reverse only all the vowels in the string and return it.
Example 1:
+The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both cases.
-Input: "hello" -Output: "holle" + +Example 1:
+Input: s = "hello" +Output: "holle" +Example 2:
+Input: s = "leetcode" +Output: "leotcede"- --- -Example 2:
- --Input: "leetcode" -Output: "leotcede"-Note:
- +
-The vowels does not include the letter "y".Constraints:
+ +
1 <= s.length <= 3 * 105
s
consist of printable ASCII characters.Given an array, rotate the array to the right by k steps, where k is non-negative.
- -Follow up:
- -Given an array, rotate the array to the right by k
steps, where k
is non-negative.
Example 1:
@@ -51,6 +44,14 @@ rotate 2 steps to the right: [3,99,-1,-100]0 <= k <= 105
Follow up:
+ +O(1)
extra space?
-Given an array of integers A
and let n to be its length.
-
You are given an integer array nums
of length n
.
-Assume Bk
to be an array obtained by rotating the array A
k positions clock-wise, we define a "rotation function" F
on A
as follow:
-
Assume arrk
to be an array obtained by rotating nums
by k
positions clock-wise. We define the rotation function F
on nums
as follow:
-F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]
.
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Calculate the maximum value of F(0), F(1), ..., F(n-1)
.
-
Return the maximum value of F(0), F(1), ..., F(n-1)
.
Note:
-n is guaranteed to be less than 105.
-
Example 1:
-Example:
-A = [4, 3, 2, 6] - +Input: nums = [4,3,2,6] +Output: 26 +Explanation: F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 - So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.- + +
Example 2:
+ ++Input: nums = [1000000007] +Output: 0 ++ + +
Constraints:
+ +n == nums.length
1 <= n <= 105
-231 <= nums[i] <= 231 - 1
You are given a 2D array of integers envelopes
where envelopes[i] = [wi, hi]
represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
+One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
-Return the maximum number of envelopes can you Russian doll (i.e., put one inside the other).
+Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
diff --git a/problems/sentence-similarity-iii/README.md b/problems/sentence-similarity-iii/README.md new file mode 100644 index 000000000..c31a6332f --- /dev/null +++ b/problems/sentence-similarity-iii/README.md @@ -0,0 +1,73 @@ + + + + + + + +[< Previous](../determine-color-of-a-chessboard-square "Determine Color of a Chessboard Square") + +[Next>](../count-nice-pairs-in-an-array "Count Nice Pairs in an Array") + +## [1813. Sentence Similarity III (Medium)](https://leetcode.com/problems/sentence-similarity-iii "句子相似性 III") + +A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World"
, "HELLO"
, "hello world hello world"
are all sentences. Words consist of only uppercase and lowercase English letters.
Two sentences sentence1
and sentence2
are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane"
and sentence2 = "Hello Jane"
can be made equal by inserting "my name is"
between "Hello"
and "Jane"
in sentence2
.
Given two sentences sentence1
and sentence2
, return true
if sentence1
and sentence2
are similar. Otherwise, return false
.
Example 1:
+ ++Input: sentence1 = "My name is Haley", sentence2 = "My Haley" +Output: true +Explanation: sentence2 can be turned to sentence1 by inserting "name is" between "My" and "Haley". ++ +
Example 2:
+ ++Input: sentence1 = "of", sentence2 = "A lot of words" +Output: false +Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other. ++ +
Example 3:
+ ++Input: sentence1 = "Eating right now", sentence2 = "Eating" +Output: true +Explanation: sentence2 can be turned to sentence1 by inserting "right now" at the end of the sentence. ++ +
Example 4:
+ ++Input: sentence1 = "Luky", sentence2 = "Lucccky" +Output: false ++ + +
Constraints:
+ +1 <= sentence1.length, sentence2.length <= 100
sentence1
and sentence2
consist of lowercase and uppercase English letters and spaces.sentence1
and sentence2
are separated by a single space.A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
+ +"Hello World"
, "HELLO"
, and "hello world hello world"
are all sentences.You are given a sentence s
and an integer k
. You want to truncate s
such that it contains only the first k
words. Return s
after truncating it.
Example 1:
+ ++Input: s = "Hello how are you Contestant", k = 4 +Output: "Hello how are you" +Explanation: +The words in s are ["Hello", "how" "are", "you", "Contestant"]. +The first 4 words are ["Hello", "how", "are", "you"]. +Hence, you should return "Hello how are you". ++ +
Example 2:
+ ++Input: s = "What is the solution to this problem", k = 4 +Output: "What is the solution" +Explanation: +The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. +The first 4 words are ["What", "is", "the", "solution"]. +Hence, you should return "What is the solution".+ +
Example 3:
+ ++Input: s = "chopper is not a tanuki", k = 5 +Output: "chopper is not a tanuki" ++ + +
Constraints:
+ +1 <= s.length <= 500
k
is in the range [1, the number of words in s]
.s
consist of only lowercase and uppercase English letters and spaces.s
are separated by a single space.Implement the class TweetCounts
that supports two methods:
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).
-1. recordTweet(string tweetName, int time)
For example, the period [10, 10000]
(in seconds) would be partitioned into the following time chunks with these frequencies:
tweetName
at the recorded time
(in seconds).[10,69]
, [70,129]
, [130,189]
, ...
, [9970,10000]
[10,3609]
, [3610,7209]
, [7210,10000]
[10,10000]
2. getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime)
Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000
in the above example).
Design and implement an API to help the company with their analysis.
+ +Implement the TweetCounts
class:
tweetName
per minute, hour, or day (depending on freq
) starting from the startTime
(in seconds) and ending at the endTime
(in seconds).freq
is always minute, hour or day, representing the time interval to get the total number of occurrences for the given tweetName
.startTime
, so the time intervals are [startTime, startTime + delta*1>, [startTime + delta*1, startTime + delta*2>, [startTime + delta*2, startTime + delta*3>, ... , [startTime + delta*i, min(startTime + delta*(i+1), endTime + 1)>
for some non-negative number i
and delta
(which depends on freq
). TweetCounts()
Initializes the TweetCounts
object.void recordTweet(String tweetName, int time)
Stores the tweetName
at the recorded time
(in seconds).List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime)
Returns a list of integers representing the number of tweets with tweetName
in each time chunk for the given period of time [startTime, endTime]
(in seconds) and frequency freq
.
+ freq
is one of "minute"
, "hour"
, or "day"
representing a frequency of every minute, hour, or day respectively.Constraints:
10000
operations considering both recordTweet
and getTweetCountsPerFrequency
.0 <= time, startTime, endTime <= 10^9
0 <= endTime - startTime <= 10^4
0 <= time, startTime, endTime <= 109
0 <= endTime - startTime <= 104
104
calls in total to recordTweet
and getTweetCountsPerFrequency
.A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
+Given an integer array data
representing the data, return whether it is a valid UTF-8 encoding.
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
+0
, followed by its Unicode code.n
bits are all one's, the n + 1
bit is 0
, followed by n - 1
bytes with the most significant 2
bits being 10
.This is how the UTF-8 encoding would work:
- Char. number range | UTF-8 octet sequence
+
+ Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
- 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
-
-
-Given an array of integers representing the data, return whether it is a valid utf-8 encoding.
-
-
-Note:
-The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
-
-
-
-Example 1:
-
-data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001.
+ 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+
+
+Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
-Return true. + +Example 1:
+ ++Input: data = [197,130,1] +Output: true +Explanation: data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.- -
-Example 2: -
-data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. +Example 2:
-Return false. -The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. -The next byte is a continuation byte which starts with 10 and that's correct. ++Input: data = [235,140,4] +Output: false +Explanation: data represented the octet sequence: 11101011 10001100 00000100. +The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. +The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid.- + + +Constraints:
+ +
1 <= data.length <= 2 * 104
0 <= data[i] <= 255
Given a wordlist
, we want to implement a spellchecker that converts a query word into a correct word.
Given a wordlist
, we want to implement a spellchecker that converts a query word into a correct word.
For a given query
word, the spell checker handles two categories of spelling mistakes:
wordlist = ["yellow"]
, query = "yellow"
: correct = "yellow"
('a', 'e', 'i', 'o', 'u')
of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.
wordlist = ["YellOw"]
, query = "yollow"
: correct = "YellOw"
wordlist = ["YellOw"]
, query = "yeellow"
: correct = ""
(no match)Given some queries
, return a list of words answer
, where answer[i]
is the correct word for query = queries[i]
.
Given some queries
, return a list of words answer
, where answer[i]
is the correct word for query = queries[i]
.
Example 1:
- --Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] -Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"]- +
Input: wordlist = ["KiTe","kite","hare","Hare"], queries = ["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"] +Output: ["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"] +
Example 2:
+Input: wordlist = ["yellow"], queries = ["YellOw"] +Output: ["yellow"] +- -
Note:
+Constraints:
1 <= wordlist.length <= 5000
1 <= queries.length <= 5000
1 <= wordlist[i].length <= 7
1 <= queries[i].length <= 7
wordlist
and queries
consist only of english letters.1 <= wordlist.length, queries.length <= 5000
1 <= wordlist[i].length, queries[i].length <= 7
wordlist[i]
and queries[i]
consist only of only English letters.You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.
+You are given two jugs with capacities jug1Capacity
and jug2Capacity
liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity
liters using these two jugs.
If z liters of water is measurable, you must have z liters of water contained within one or both buckets by the end.
+If targetCapacity
liters of water are measurable, you must have targetCapacity
liters of water contained within one or both buckets by the end.
Operations allowed:
Example 1: (From the famous "Die Hard" example)
+ +Example 1:
+ ++Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 +Output: true +Explanation: The famous Die Hard example ++ +
Example 2:
-Input: x = 3, y = 5, z = 4 -Output: True +Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 +Output: false-
Example 2:
+Example 3:
-Input: x = 2, y = 6, z = 5 -Output: False +Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 +Output: true+
Constraints:
0 <= x <= 10^6
0 <= y <= 10^6
0 <= z <= 10^6
1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106
Given an integer array nums
, return the length of the longest wiggle sequence.
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
+A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with two or fewer elements is trivially a wiggle sequence.
[1, 7, 4, 9, 2, 5]
is a wiggle sequence because the differences (6, -3, 5, -7, 3)
are alternately positive and negative.[1, 4, 7, 2, 5]
and [1, 7, 4, 5, 5]
are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.[1, 7, 4, 9, 2, 5]
is a wiggle sequence because the differences (6, -3, 5, -7, 3)
alternate between positive and negative.[1, 4, 7, 2, 5]
and [1, 7, 4, 5, 5]
are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.A subsequence is obtained by deleting some elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
+A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
+ +Given an integer array nums
, return the length of the longest wiggle subsequence of nums
.
Example 1:
@@ -28,7 +28,7 @@Input: nums = [1,7,4,9,2,5] Output: 6 -Explanation: The entire sequence is a wiggle sequence. +Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
Example 2:
@@ -36,7 +36,8 @@Input: nums = [1,17,5,10,13,15,10,5,16,8] Output: 7 -Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. +Explanation: There are several subsequences that achieve this length. +One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
Example 3:
diff --git a/problems/word-search/README.md b/problems/word-search/README.md index 7d0419bff..5435a6bf0 100644 --- a/problems/word-search/README.md +++ b/problems/word-search/README.md @@ -15,8 +15,6 @@The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
-Note: There will be some test cases with a board
or a word
larger than constraints to test if your solution is using pruning.
Example 1:
@@ -50,6 +48,9 @@board
and word
consists of only lowercase and uppercase English letters.Follow up: Could you use search pruning to make your solution faster with a larger board
?