mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
refactor(work): restructure solution directories with bucket level and add .gitkeep placeholders
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
11. Container With Most Water
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/container-with-most-water/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an integer array height of length n. There are n
|
||||
vertical lines drawn such that the two endpoints of the i^th line are
|
||||
(i, 0) and (i, height[i]).
|
||||
|
||||
Find two lines that together with the x-axis form a container, such
|
||||
that the container contains the most water.
|
||||
|
||||
Return the maximum amount of water a container can store.
|
||||
|
||||
Notice that you may not slant the container.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: height = [1,8,6,2,5,4,8,3,7]
|
||||
Output: 49
|
||||
Explanation: The above vertical lines are represented by array
|
||||
[1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue
|
||||
section) the container can contain is 49.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: height = [1,1]
|
||||
Output: 1
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• n == height.length
|
||||
|
||||
• 2 <= n <= 10^5
|
||||
|
||||
• 0 <= height[i] <= 10^4
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def maxArea(self, height: List[int]) -> int: # noqa: F821
|
||||
res = 0
|
||||
left = 0
|
||||
right = len(height) - 1
|
||||
|
||||
while left < right:
|
||||
area = (right - left) * min(height[left], height[right])
|
||||
res = max(res, area)
|
||||
if height[left] < height[right]:
|
||||
left += 1
|
||||
else:
|
||||
right -= 1
|
||||
|
||||
return res
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
15. 3Sum
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/3sum/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [-1,0,1,2,-1,-4]
|
||||
Output: [[-1,-1,2],[-1,0,1]]
|
||||
Explanation:
|
||||
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
|
||||
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
|
||||
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
|
||||
The distinct triplets are [-1,0,1] and [-1,-1,2].
|
||||
Notice that the order of the output and the order of the triplets
|
||||
does not matter.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: nums = [0,1,1]
|
||||
Output: []
|
||||
Explanation: The only possible triplet does not sum up to 0.
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: nums = [0,0,0]
|
||||
Output: [[0,0,0]]
|
||||
Explanation: The only possible triplet sums up to 0.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 3 <= nums.length <= 3000
|
||||
|
||||
• -10^5 <= nums[i] <= 10^5
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def threeSum(self, nums: list[int]) -> list[list[int]]:
|
||||
nums.sort()
|
||||
result = []
|
||||
n = len(nums)
|
||||
|
||||
for i in range(n):
|
||||
# skip all zero
|
||||
if i > 0 and nums[i] == nums[i - 1]:
|
||||
continue
|
||||
|
||||
# two pointers
|
||||
left = i + 1
|
||||
right = n - 1
|
||||
target = -nums[i]
|
||||
|
||||
while left < right:
|
||||
current = nums[left] + nums[right]
|
||||
|
||||
if current == target:
|
||||
result.append([nums[i], nums[left], nums[right]])
|
||||
|
||||
# skip duplicates
|
||||
while left < right and nums[left] == nums[left + 1]:
|
||||
left += 1
|
||||
while left < right and nums[right] == nums[right - 1]:
|
||||
right -= 1
|
||||
|
||||
# shift pointers
|
||||
left += 1
|
||||
right -= 1
|
||||
|
||||
# since sorted, if current < target, then move left
|
||||
elif current < target:
|
||||
left += 1
|
||||
# since sorted, if current > target, then move right
|
||||
else:
|
||||
right -= 1
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
150. Evaluate Reverse Polish Notation
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/evaluate-reverse-polish-notation/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an array of strings tokens that represents an
|
||||
arithmetic expression in a Reverse Polish Notation.
|
||||
|
||||
Evaluate the expression. Return an integer that represents the value
|
||||
of the expression.
|
||||
|
||||
Note that:
|
||||
|
||||
• The valid operators are '+', '-', '*', and '/'.
|
||||
|
||||
• Each operand may be an integer or another expression.
|
||||
|
||||
• The division between two integers always truncates toward zero.
|
||||
|
||||
• There will not be any division by zero.
|
||||
|
||||
• The input represents a valid arithmetic expression in a reverse
|
||||
polish notation.
|
||||
|
||||
• The answer and all the intermediate calculations can be
|
||||
represented in a 32-bit integer.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: tokens = ["2","1","+","3","*"]
|
||||
Output: 9
|
||||
Explanation: ((2 + 1) * 3) = 9
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: tokens = ["4","13","5","/","+"]
|
||||
Output: 6
|
||||
Explanation: (4 + (13 / 5)) = 6
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: tokens =
|
||||
["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
|
||||
Output: 22
|
||||
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
|
||||
= ((10 * (6 / (12 * -11))) + 17) + 5
|
||||
= ((10 * (6 / -132)) + 17) + 5
|
||||
= ((10 * 0) + 17) + 5
|
||||
= (0 + 17) + 5
|
||||
= 17 + 5
|
||||
= 22
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 1 <= tokens.length <= 10^4
|
||||
|
||||
• tokens[i] is either an operator: "+", "-", "*", or "/", or an
|
||||
integer in the range [-200, 200].
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def evalRPN(self, tokens: List[str]) -> int:
|
||||
stack = []
|
||||
operations = {
|
||||
"+": lambda x, y: int(x + y),
|
||||
"-": lambda x, y: int(x - y),
|
||||
"*": lambda x, y: int(x * y),
|
||||
"/": lambda x, y: int(x / y),
|
||||
}
|
||||
|
||||
for c in tokens:
|
||||
if c in operations:
|
||||
y = stack.pop()
|
||||
x = stack.pop()
|
||||
calc_func = operations[c]
|
||||
result = calc_func(x, y)
|
||||
stack.append(result)
|
||||
else:
|
||||
stack.append(int(c))
|
||||
|
||||
return stack[0]
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
153. Find Minimum in Rotated Sorted Array
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Suppose an array of length n sorted in ascending order is rotated
|
||||
between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7]
|
||||
might become:
|
||||
|
||||
• [4,5,6,7,0,1,2] if it was rotated 4 times.
|
||||
|
||||
• [0,1,2,4,5,6,7] if it was rotated 7 times.
|
||||
|
||||
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time
|
||||
results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
|
||||
|
||||
Given the sorted rotated array nums of unique elements, return the
|
||||
minimum element of this array.
|
||||
|
||||
You must write an algorithm that runs in O(log n) time.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: nums = [3,4,5,1,2]
|
||||
Output: 1
|
||||
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: nums = [4,5,6,7,0,1,2]
|
||||
Output: 0
|
||||
Explanation: The original array was [0,1,2,4,5,6,7] and it was
|
||||
rotated 4 times.
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: nums = [11,13,15,17]
|
||||
Output: 11
|
||||
Explanation: The original array was [11,13,15,17] and it was rotated
|
||||
4 times.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• n == nums.length
|
||||
|
||||
• 1 <= n <= 5000
|
||||
|
||||
• -5000 <= nums[i] <= 5000
|
||||
|
||||
• All the integers of nums are unique.
|
||||
|
||||
• nums is sorted and rotated between 1 and n times.
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def findMin(self, nums: List[int]) -> int:
|
||||
l, r = 0, len(nums) - 1
|
||||
lowest_index = -1
|
||||
|
||||
while l <= r:
|
||||
m = (l + r) // 2
|
||||
if nums[m] <= nums[-1]:
|
||||
lowest_index = m
|
||||
r = m - 1
|
||||
else:
|
||||
l = m + 1
|
||||
|
||||
return nums[lowest_index]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
167. Two Sum II - Input Array Is Sorted
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given a 1-indexed 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. Let these two numbers be numbers[index1] and
|
||||
numbers[index2] where 1 <= index1 < index2 <= numbers.length.
|
||||
|
||||
Return the indices of the two numbers index1 and index2, each
|
||||
incremented by one, as an integer array [index1, index2] of length 2.
|
||||
|
||||
The tests are generated such that there is exactly one solution. You
|
||||
may not use the same element twice.
|
||||
|
||||
Your solution must use only constant extra space.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: numbers = [2,7,11,15], target = 9
|
||||
Output: [1,2]
|
||||
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 =
|
||||
2. We return [1, 2].
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: numbers = [2,3,4], target = 6
|
||||
Output: [1,3]
|
||||
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 =
|
||||
3. We return [1, 3].
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: numbers = [-1,0], target = -1
|
||||
Output: [1,2]
|
||||
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2
|
||||
= 2. We return [1, 2].
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• 2 <= numbers.length <= 3 * 10^4
|
||||
|
||||
• -1000 <= numbers[i] <= 1000
|
||||
|
||||
• numbers is sorted in non-decreasing order.
|
||||
|
||||
• -1000 <= target <= 1000
|
||||
|
||||
• The tests are generated such that there is exactly one solution.
|
||||
"""
|
||||
|
||||
class Solution:
|
||||
def twoSum(self, numbers: List[int], target: int) -> List[int]:
|
||||
i = 0
|
||||
j = len(numbers) - 1
|
||||
|
||||
while i < j:
|
||||
c = numbers[i] + numbers[j]
|
||||
if c == target:
|
||||
return [i + 1, j + 1]
|
||||
elif c < target:
|
||||
i+=1
|
||||
else:
|
||||
j-=1
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 238. Product of Array Except Self
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/product-of-array-except-self/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array nums, return an array answer such that
|
||||
* answer[i] is equal to the product of all the elements of nums except
|
||||
* nums[i].
|
||||
*
|
||||
* The product of any prefix or suffix of nums is guaranteed to fit in a
|
||||
* 32-bit integer.
|
||||
*
|
||||
* You must write an algorithm that runs in O(n) time and without using
|
||||
* the division operation.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,2,3,4]
|
||||
* Output: [24,12,8,6]
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [-1,1,0,-3,3]
|
||||
* Output: [0,0,9,0,0]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 2 <= nums.length <= 10^5
|
||||
*
|
||||
* • -30 <= nums[i] <= 30
|
||||
*
|
||||
* • The input is generated such that answer[i] is guaranteed to fit in
|
||||
* a 32-bit integer.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Follow up: Can you solve the problem in O(1) extra space complexity?
|
||||
* (The output array does not count as extra space for space complexity
|
||||
* analysis.)
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @return {number[]}
|
||||
*/
|
||||
var productExceptSelf = function(nums) {
|
||||
const n = nums.length;
|
||||
const answer = new Array(n).fill(1);
|
||||
const rightArr = new Array(n).fill(1);
|
||||
|
||||
for (let i = 1; i < n; i++) {
|
||||
answer[i] = nums[i - 1] * answer[i - 1];
|
||||
}
|
||||
for (let i = n - 2; i >= 0; i--) {
|
||||
rightArr[i] = nums[i + 1] * rightArr[i + 1];
|
||||
}
|
||||
for (let i = 0; i < n; i++) {
|
||||
answer[i] *= rightArr[i];
|
||||
}
|
||||
return answer;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 33. Search in Rotated Sorted Array
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/search-in-rotated-sorted-array/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* There is an integer array nums sorted in ascending order (with
|
||||
* distinct values).
|
||||
*
|
||||
* Prior to being passed to your function, nums is possibly left rotated
|
||||
* at an unknown index k (1 <= k < nums.length) such that the resulting
|
||||
* array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ...,
|
||||
* nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left
|
||||
* rotated by 3 indices and become [4,5,6,7,0,1,2].
|
||||
*
|
||||
* Given the array nums after the possible rotation and an integer
|
||||
* target, return the index of target if it is in nums, or -1 if it is
|
||||
* not in nums.
|
||||
*
|
||||
* You must write an algorithm with O(log n) runtime complexity.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [4,5,6,7,0,1,2], target = 0
|
||||
* Output: 4
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [4,5,6,7,0,1,2], target = 3
|
||||
* Output: -1
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [1], target = 0
|
||||
* Output: -1
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 5000
|
||||
*
|
||||
* • -10^4 <= nums[i] <= 10^4
|
||||
*
|
||||
* • All values of nums are unique.
|
||||
*
|
||||
* • nums is an ascending array that is possibly rotated.
|
||||
*
|
||||
* • -10^4 <= target <= 10^4
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @param {number} target
|
||||
* @return {number}
|
||||
*/
|
||||
var search = function(nums, target) {
|
||||
let l = 0, r = nums.length - 1;
|
||||
|
||||
while (l <= r){
|
||||
let mid = Math.floor((l + r)/2);
|
||||
if (target === nums[mid]) {
|
||||
return mid
|
||||
}
|
||||
|
||||
// Left sorted portion
|
||||
if (nums[l] <= nums[mid]){
|
||||
if (target > nums[mid] || target < nums[l]){
|
||||
l = mid + 1;
|
||||
}else{
|
||||
r = mid - 1;
|
||||
}
|
||||
}
|
||||
// Right sorted portion
|
||||
else{
|
||||
if(target < nums[mid] || target > nums[r]){
|
||||
r = mid - 1;
|
||||
}else{
|
||||
l = mid + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* 347. Top K Frequent Elements
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/top-k-frequent-elements/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an integer array nums and an integer k, return the k most
|
||||
* frequent elements. You may return the answer in any order.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,1,1,2,2,3], k = 2
|
||||
*
|
||||
* Output: [1,2]
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [1], k = 1
|
||||
*
|
||||
* Output: [1]
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
|
||||
*
|
||||
* Output: [1,2]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 10^5
|
||||
*
|
||||
* • -10^4 <= nums[i] <= 10^4
|
||||
*
|
||||
* • k is in the range [1, the number of unique elements in the array].
|
||||
*
|
||||
* • It is guaranteed that the answer is unique.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Follow up: Your algorithm's time complexity must be better than O(n
|
||||
* log n), where n is the array's size.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @param {number} k
|
||||
* @return {number[]}
|
||||
*/
|
||||
var topKFrequent = function (nums, k) {
|
||||
const freq = {};
|
||||
for (let n of nums) freq[n] = (freq[n] || 0) + 1;
|
||||
|
||||
return Object.keys(freq)
|
||||
.map(Number)
|
||||
.sort((a, b) => freq[b] - freq[a])
|
||||
.slice(0, k);
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 49. Group Anagrams
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/group-anagrams/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array of strings strs, group the anagrams together. You can
|
||||
* return the answer in any order.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: strs = ["eat","tea","tan","ate","nat","bat"]
|
||||
*
|
||||
* Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
|
||||
*
|
||||
* Explanation:
|
||||
*
|
||||
* • There is no string in strs that can be rearranged to form "bat".
|
||||
*
|
||||
* • The strings "nat" and "tan" are anagrams as they can be rearranged
|
||||
* to form each other.
|
||||
*
|
||||
* • The strings "ate", "eat", and "tea" are anagrams as they can be
|
||||
* rearranged to form each other.
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: strs = [""]
|
||||
*
|
||||
* Output: [[""]]
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: strs = ["a"]
|
||||
*
|
||||
* Output: [["a"]]
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= strs.length <= 10^4
|
||||
*
|
||||
* • 0 <= strs[i].length <= 100
|
||||
*
|
||||
* • strs[i] consists of lowercase English letters.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string[]} strs
|
||||
* @return {string[][]}
|
||||
*/
|
||||
var groupAnagrams = function(strs) {
|
||||
let sorted = strs.map(str => str.split("").sort().join(""));
|
||||
let anagrams = {};
|
||||
|
||||
for (let i = 0; i < strs.length; i++){
|
||||
if(!anagrams[sorted[i]]){
|
||||
anagrams[sorted[i]] = [strs[i]]
|
||||
}else{
|
||||
anagrams[sorted[i]].push(strs[i])
|
||||
}
|
||||
}
|
||||
|
||||
return Object.values(anagrams);
|
||||
};
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 560. Subarray Sum Equals K
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/subarray-sum-equals-k/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Given an array of integers nums and an integer k, return the total
|
||||
* number of subarrays whose sum equals to k.
|
||||
*
|
||||
* A subarray is a contiguous non-empty sequence of elements within an
|
||||
* array.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: nums = [1,1,1], k = 2
|
||||
* Output: 2
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: nums = [1,2,3], k = 3
|
||||
* Output: 2
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= nums.length <= 2 * 10^4
|
||||
*
|
||||
* • -1000 <= nums[i] <= 1000
|
||||
*
|
||||
* • -10^7 <= k <= 10^7
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} nums
|
||||
* @param {number} k
|
||||
* @return {number}
|
||||
*/
|
||||
var subarraySum = function(nums, k) {
|
||||
const map = new Map();
|
||||
map.set(0, 1);
|
||||
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
|
||||
for (let n of nums){
|
||||
sum += n;
|
||||
|
||||
if(map.has(sum - k)){
|
||||
count += map.get(sum - k);
|
||||
}
|
||||
|
||||
map.set(sum, (map.get(sum) || 0) + 1);
|
||||
}
|
||||
return count
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
739. Daily Temperatures
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/daily-temperatures/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
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 i^th 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 <= 10^5
|
||||
|
||||
• 30 <= temperatures[i] <= 100
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
|
||||
ans = [0] * len(temperatures)
|
||||
stack = []
|
||||
for i, temp in enumerate(temperatures):
|
||||
while stack and temperatures[stack[-1]] < temp:
|
||||
prev = stack.pop()
|
||||
ans[prev] = i - prev
|
||||
stack.append(i)
|
||||
return ans
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
74. Search a 2D Matrix
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/search-a-2d-matrix/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given an m x n integer matrix matrix with the following two
|
||||
properties:
|
||||
|
||||
• Each row is sorted in non-decreasing order.
|
||||
|
||||
• The first integer of each row is greater than the last integer of
|
||||
the previous row.
|
||||
|
||||
Given an integer target, return true if target is in matrix or false
|
||||
otherwise.
|
||||
|
||||
You must write a solution in O(log(m * n)) time complexity.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
|
||||
Output: true
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
|
||||
Output: false
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• m == matrix.length
|
||||
|
||||
• n == matrix[i].length
|
||||
|
||||
• 1 <= m, n <= 100
|
||||
|
||||
• -10^4 <= matrix[i][j], target <= 10^4
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
|
||||
ROWS, COLS = len(matrix), len(matrix[0])
|
||||
|
||||
top, bot = 0, ROWS - 1
|
||||
while top <= bot:
|
||||
row = (top + bot) // 2
|
||||
if target > matrix[row][-1]:
|
||||
top = row + 1
|
||||
elif target < matrix[row][0]:
|
||||
bot = row - 1
|
||||
else:
|
||||
break
|
||||
|
||||
if not (top <= bot):
|
||||
return False
|
||||
|
||||
row = (top + bot) // 2
|
||||
l, r = 0, COLS - 1
|
||||
while l <= r:
|
||||
m = (l + r) // 2
|
||||
if target > matrix[row][m]:
|
||||
l = m + 1
|
||||
elif target < matrix[row][m]:
|
||||
r = m - 1
|
||||
else:
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
853. Car Fleet
|
||||
Difficulty: Medium
|
||||
https://leetcode.com/problems/car-fleet/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
There are n cars at given miles away from the starting mile 0,
|
||||
traveling to reach the mile target.
|
||||
|
||||
You are given two integer arrays position and speed, both of length
|
||||
n, where position[i] is the starting mile of the i^th car and speed[i]
|
||||
is the speed of the i^th car in miles per hour.
|
||||
|
||||
A car cannot pass another car, but it can catch up and then travel
|
||||
next to it at the speed of the slower car.
|
||||
|
||||
A car fleet is a single car or a group of cars driving next to each
|
||||
other. The speed of the car fleet is the minimum speed of any car in
|
||||
the fleet.
|
||||
|
||||
If a car catches up to a car fleet at the mile target, it will still
|
||||
be considered as part of the car fleet.
|
||||
|
||||
Return the number of car fleets that will arrive at the destination.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
|
||||
|
||||
Output: 3
|
||||
|
||||
Explanation:
|
||||
|
||||
• The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet,
|
||||
meeting each other at 12. The fleet forms at target.
|
||||
|
||||
• The car starting at 0 (speed 1) does not catch up to any other
|
||||
car, so it is a fleet by itself.
|
||||
|
||||
• The cars starting at 5 (speed 1) and 3 (speed 3) become a fleet,
|
||||
meeting each other at 6. The fleet moves at speed 1 until it reaches
|
||||
target.
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: target = 10, position = [3], speed = [3]
|
||||
|
||||
Output: 1
|
||||
|
||||
Explanation:
|
||||
|
||||
There is only one car, hence there is only one fleet.
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: target = 100, position = [0,2,4], speed = [4,2,1]
|
||||
|
||||
Output: 1
|
||||
|
||||
Explanation:
|
||||
|
||||
• The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet,
|
||||
meeting each other at 4. The car starting at 4 (speed 1) travels to 5.
|
||||
|
||||
• Then, the fleet at 4 (speed 2) and the car at position 5 (speed 1)
|
||||
become one fleet, meeting each other at 6. The fleet moves at speed 1
|
||||
until it reaches target.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• n == position.length == speed.length
|
||||
|
||||
• 1 <= n <= 10^5
|
||||
|
||||
• 0 < target <= 10^6
|
||||
|
||||
• 0 <= position[i] < target
|
||||
|
||||
• All the values of position are unique.
|
||||
|
||||
• 0 < speed[i] <= 10^6
|
||||
"""
|
||||
|
||||
|
||||
class Solution:
|
||||
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
|
||||
stack = []
|
||||
for pos, spd in sorted(zip(position, speed), reverse=True):
|
||||
time = (target - pos) / spd
|
||||
if not stack or time > stack[-1]:
|
||||
stack.append(time)
|
||||
|
||||
return len(stack)
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 875. Koko Eating Bananas
|
||||
* Difficulty: Medium
|
||||
* https://leetcode.com/problems/koko-eating-bananas/
|
||||
*
|
||||
* ──────────────────────────────────────────────────
|
||||
*
|
||||
* Koko loves to eat bananas. There are n piles of bananas, the i^th
|
||||
* pile has piles[i] bananas. The guards have gone and will come back in
|
||||
* h hours.
|
||||
*
|
||||
* Koko can decide her bananas-per-hour eating speed of k. Each hour,
|
||||
* she chooses some pile of bananas and eats k bananas from that pile. If
|
||||
* the pile has less than k bananas, she eats all of them instead and
|
||||
* will not eat any more bananas during this hour.
|
||||
*
|
||||
* Koko likes to eat slowly but still wants to finish eating all the
|
||||
* bananas before the guards return.
|
||||
*
|
||||
* Return the minimum integer k such that she can eat all the bananas
|
||||
* within h hours.
|
||||
*
|
||||
*
|
||||
*
|
||||
* Example 1:
|
||||
*
|
||||
* Input: piles = [3,6,7,11], h = 8
|
||||
* Output: 4
|
||||
*
|
||||
* Example 2:
|
||||
*
|
||||
* Input: piles = [30,11,23,4,20], h = 5
|
||||
* Output: 30
|
||||
*
|
||||
* Example 3:
|
||||
*
|
||||
* Input: piles = [30,11,23,4,20], h = 6
|
||||
* Output: 23
|
||||
*
|
||||
*
|
||||
*
|
||||
* Constraints:
|
||||
*
|
||||
* • 1 <= piles.length <= 10^4
|
||||
*
|
||||
* • piles.length <= h <= 10^9
|
||||
*
|
||||
* • 1 <= piles[i] <= 10^9
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {number[]} piles
|
||||
* @param {number} h
|
||||
* @return {number}
|
||||
*/
|
||||
var minEatingSpeed = function(piles, h) {
|
||||
// Function to determine if K works for the H
|
||||
function kWorks(k){
|
||||
let hours = 0;
|
||||
for (let p of piles){
|
||||
hours += Math.ceil(p/k)
|
||||
}
|
||||
return hours <= h;
|
||||
}
|
||||
|
||||
// Setup Binary Search
|
||||
let l = 1;
|
||||
let r = Math.max(...piles);
|
||||
|
||||
// Find the K value which works for H and consumes all bananas
|
||||
while (l < r){
|
||||
const mid = Math.floor((l + r) / 2);
|
||||
if (kWorks(mid)){
|
||||
r = mid;
|
||||
}else{
|
||||
l = mid + 1;
|
||||
}
|
||||
}
|
||||
return l;
|
||||
};
|
||||
Reference in New Issue
Block a user